That is very odd.
I went through ItemNotFoundException
's base classes and tested the following multiple catch
es to see what would catch it:
try {
remove-item C:\nonexistent\file.txt -erroraction stop
}
catch [System.Management.Automation.ItemNotFoundException] {
write-host 'ItemNotFound'
}
catch [System.Management.Automation.SessionStateException] {
write-host 'SessionState'
}
catch [System.Management.Automation.RuntimeException] {
write-host 'RuntimeException'
}
catch [System.SystemException] {
write-host 'SystemException'
}
catch [System.Exception] {
write-host 'Exception'
}
catch {
write-host 'well, darn'
}
As it turns out, the output was 'RuntimeException'
. I also tried it with a different exception CommandNotFoundException
:
try {
do-nonexistent-command
}
catch [System.Management.Automation.CommandNotFoundException] {
write-host 'CommandNotFoundException'
}
catch {
write-host 'well, darn'
}
That output 'CommandNotFoundException'
correctly.
I vaguely remember reading elsewhere (though I couldn't find it again) of problems with this. In such cases where exception filtering didn't work correctly, they would catch the closest Type
they could and then use a switch
. The following just catches Exception
instead of RuntimeException
, but is the switch
equivalent of my first example that checks all base types of ItemNotFoundException
:
try {
Remove-Item C:\nonexistent\file.txt -ErrorAction Stop
}
catch [System.Exception] {
switch($_.Exception.GetType().FullName) {
'System.Management.Automation.ItemNotFoundException' {
write-host 'ItemNotFound'
}
'System.Management.Automation.SessionStateException' {
write-host 'SessionState'
}
'System.Management.Automation.RuntimeException' {
write-host 'RuntimeException'
}
'System.SystemException' {
write-host 'SystemException'
}
'System.Exception' {
write-host 'Exception'
}
default {'well, darn'}
}
}
This writes 'ItemNotFound'
, as it should.
Based on the previous reply, mainly @fcalderan, this marquee scrolls when hovered, with the advantage that the animation scrolls completely even if the text is shorter than the space within it scrolls, also any text length takes the same amount of time (this may be a pros or a cons) when not hovered the text return in the initial position.
No hardcoded value other than the scroll time, best suited for small scroll spaces
.marquee {_x000D_
width: 100%;_x000D_
margin: 0 auto;_x000D_
white-space: nowrap;_x000D_
overflow: hidden;_x000D_
box-sizing: border-box;_x000D_
display: inline-flex; _x000D_
}_x000D_
_x000D_
.marquee span {_x000D_
display: flex; _x000D_
flex-basis: 100%;_x000D_
animation: marquee-reset;_x000D_
animation-play-state: paused; _x000D_
}_x000D_
_x000D_
.marquee:hover> span {_x000D_
animation: marquee 2s linear infinite;_x000D_
animation-play-state: running;_x000D_
}_x000D_
_x000D_
@keyframes marquee {_x000D_
0% {_x000D_
transform: translate(0%, 0);_x000D_
} _x000D_
50% {_x000D_
transform: translate(-100%, 0);_x000D_
}_x000D_
50.001% {_x000D_
transform: translate(100%, 0);_x000D_
}_x000D_
100% {_x000D_
transform: translate(0%, 0);_x000D_
}_x000D_
}_x000D_
@keyframes marquee-reset {_x000D_
0% {_x000D_
transform: translate(0%, 0);_x000D_
} _x000D_
}
_x000D_
<span class="marquee">_x000D_
<span>This is the marquee text</span>_x000D_
</span>
_x000D_
If you're using Windows it's not possible - read below. You can use the local address of your machine instead and then you'll be able to capture stuff. See CaptureSetup/Loopback.
Summary: you can capture on the loopback interface on Linux, on various BSDs including Mac OS X, and on Digital/Tru64 UNIX, and you might be able to do it on Irix and AIX, but you definitely cannot do so on Solaris, HP-UX....
Although the page mentions that this is not possible on Windows using Wireshark alone, you can actually record it using a workaround as mentioned in a different answer.
EDIT: Some 3 years later, this answer is no longer completely correct. The linked page contains instructions for capturing on the loopback interface.
Your understanding is incorrect, in cases like these always consult the JavaDoc.
assertFalse
public static void assertFalse(java.lang.String message, boolean condition)
Asserts that a condition is false. If it isn't it throws an AssertionError with the given message.
Parameters:
message
- the identifying message for the AssertionError (null okay)condition
- condition to be checked
In Swift:
override func viewDidLoad() {
super.viewDidLoad()
// We set the table view header.
let cellTableViewHeader = tableView.dequeueReusableCellWithIdentifier(TableViewController.tableViewHeaderCustomCellIdentifier) as! UITableViewCell
cellTableViewHeader.frame = CGRectMake(0, 0, self.tableView.bounds.width, self.heightCache[TableViewController.tableViewHeaderCustomCellIdentifier]!)
self.tableView.tableHeaderView = cellTableViewHeader
// We set the table view footer, just know that it will also remove extra cells from tableview.
let cellTableViewFooter = tableView.dequeueReusableCellWithIdentifier(TableViewController.tableViewFooterCustomCellIdentifier) as! UITableViewCell
cellTableViewFooter.frame = CGRectMake(0, 0, self.tableView.bounds.width, self.heightCache[TableViewController.tableViewFooterCustomCellIdentifier]!)
self.tableView.tableFooterView = cellTableViewFooter
}
This is a bit late but I know it will help someone:
If you are using datetimepicker
make sure you include the right CSS and JS files. datetimepicker
uses(Take note of their names);
and
On the above question asked by @mindfreak,The main problem is due to the imported files.
$("input").on("keydown",function search(e) {
if(e.keyCode == 13) {
alert($(this).val());
}
});
jsFiddle example : http://jsfiddle.net/NH8K2/1/
callLog(){
this.http.get('http://localhost:3000/getstudent/'+this.login.email+'/'+this.login.password)
.subscribe(data => {
this.getstud=data as string[];
if(this.getstud.length!==0) {
console.log(data)
this.route.navigate(['home']);// used for routing after importing Router
}
});
}
I agree with @Marlon. When you compile your C# project with the Release configuration, you will find into the "bin/Release" folder of your project the executable of your application. This SHOULD work for a simple application.
But, if your application have any dependencies on some external dll, I suggest you to create a SetupProject with VisualStudio. Doing so, the project wizard will find all dependencies of your application and add them (the librairies) to the installation folder. Finally, all you will have to do is run the setup on the users computer and install your software.
public static void replaceFileString(String old, String new) throws IOException {
String fileName = Settings.getValue("fileDirectory");
FileInputStream fis = new FileInputStream(fileName);
String content = IOUtils.toString(fis, Charset.defaultCharset());
content = content.replaceAll(old, new);
FileOutputStream fos = new FileOutputStream(fileName);
IOUtils.write(content, new FileOutputStream(fileName), Charset.defaultCharset());
fis.close();
fos.close();
}
above is my implementation of Meriton's example that works for me. The fileName is the directory (ie. D:\utilities\settings.txt). I'm not sure what character set should be used, but I ran this code on a Windows XP machine just now and it did the trick without doing that temporary file creation and renaming stuff.
Whenever possible I would shift all of the querying to the backend on the server (to the SQL DB or other native database type). Reason being is that it will be quicker and more optimized to do the querying.
I know that jSON can be stand alone and there may be +/- for having a querying language but I cannot see the advantage if you are retrieving data from the backend to a browser, as most of the JSON use cases. Query and filter at the backend to get as small a data that is needed.
If for whatever reason you need to query at the front-end (mostly in a browser) then I would suggest just using array.filter (why invent something else?).
That said what I think would be more useful is a transformation API for json...they are more useful since once you have the data you may want to display it in a number of ways. However, again, you can do much of this on the server (which can be much easier to scale) than on the client - IF you are using server<-->client model.
Just my 2 pence worth!
This is also helpful when exposing a public interface. If you have a method like this,
public ArrayList getList();
Then you decide to change it to,
public LinkedList getList();
Anyone who was doing ArrayList list = yourClass.getList()
will need to change their code. On the other hand, if you do,
public List getList();
Changing the implementation doesn't change anything for the users of your API.
Be aware that all the solutions where you pass a string containing user provided values to system
, %x[]
etc. are unsafe! Unsafe actually means: the user may trigger code to run in the context and with all permissions of the program.
As far as I can say only system
and Open3.popen3
do provide a secure/escaping variant in Ruby 1.8. In Ruby 1.9 IO::popen
also accepts an array.
Simply pass every option and argument as an array to one of these calls.
If you need not just the exit status but also the result you probably want to use Open3.popen3
:
require 'open3'
stdin, stdout, stderr, wait_thr = Open3.popen3('usermod', '-p', @options['shadow'], @options['username'])
stdout.gets(nil)
stdout.close
stderr.gets(nil)
stderr.close
exit_code = wait_thr.value
Note that the block form will auto-close stdin, stdout and stderr- otherwise they'd have to be closed explicitly.
More information here: Forming sanitary shell commands or system calls in Ruby
Try this if you must use switch.
public static int range(int num){
if ( 10 < num && num < 20)
return 1;
if ( 20 <= num && num < 30)
return 2;
return 3;
}
public static final int TEN_TWENTY = 1;
public static final int TWENTY_THIRTY = 2;
public static void main(String[]args){
int a = 110;
switch (range(a)){
case TEN_TWENTY:
System.out.println("10-20");
break;
case TWENTY_THIRTY:
System.out.println("20-30");
break;
default: break;
}
}
One more possible reason if you are using Tycho and Maven to build bundles, that you have wrong execution environment (Bundle-RequiredExecutionEnvironment
) in the manifest file (manifest.mf
) defined. For example:
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Engine Plug-in
Bundle-SymbolicName: com.foo.bar
Bundle-Version: 4.6.5.qualifier
Bundle-Activator: com.foo.bar.Activator
Bundle-Vendor: Foobar Technologies Ltd.
Require-Bundle: org.eclipse.core.runtime,
org.jdom;bundle-version="1.0.0",
org.apache.commons.codec;bundle-version="1.3.0",
bcprov-ext;bundle-version="1.47.0"
Bundle-RequiredExecutionEnvironment: JavaSE-1.5
Export-Package: ...
...
Import-Package: ...
...
In my case everything else was ok. The compiler plugins (normal maven and tycho as well) were set correctly, still m2 generated old compliance level because of the manifest. I thought I share the experience.
Try this jsfiddle:
$(function() {
$('#cd').click(function () {
$('#dsf').val('Changed Value');
});
});
The term ABI is used to refer to two distinct but related concepts.
When talking about compilers it refers to the rules used to translate from source-level constructs to binary constructs. How big are the data types? how does the stack work? how do I pass parameters to functions? which registers should be saved by the caller vs the callee?
When talking about libraries it refers to the binary interface presented by a compiled library. This interface is the result of a number of factors including the source code of the library, the rules used by the compiler and in some cases definitions picked up from other libraries.
Changes to a library can break the ABI without breaking the API. Consider for example a library with an interface like.
void initfoo(FOO * foo)
int usefoo(FOO * foo, int bar)
void cleanupfoo(FOO * foo)
and the application programmer writes code like
int dostuffwithfoo(int bar) {
FOO foo;
initfoo(&foo);
int result = usefoo(&foo,bar)
cleanupfoo(&foo);
return result;
}
The application programmer doesn't care about the size or layout of FOO, but the application binary ends up with a hardcoded size of foo. If the library programmer adds an extra field to foo and someone uses the new library binary with the old application binary then the library may make out of bounds memory accesses.
OTOH if the library author had designed their API like.
FOO * newfoo(void)
int usefoo(FOO * foo, int bar)
void deletefoo((FOO * foo, int bar))
and the application programmer writes code like
int dostuffwithfoo(int bar) {
FOO * foo;
foo = newfoo();
int result = usefoo(foo,bar)
deletefoo(foo);
return result;
}
Then the application binary does not need to know anything about the structure of FOO, that can all be hidden inside the library. The price you pay for that though is that heap operations are involved.
I also saw this change on my Mac when I went from running pip
to sudo pip
. Adding -H
to sudo causes the message to go away for me. E.g.
sudo -H pip install foo
man sudo
tells me that -H
causes sudo
to set $HOME
to the target users (root in this case).
So it appears pip is looking into $HOME/Library/Log
and sudo
by default isn't setting $HOME
to /root/
. Not surprisingly ~/Library/Log
is owned by you as a user rather than root.
I suspect this is some recent change in pip. I'll run it with sudo -H
for now to work around.
Type sudo apt-get install moreutils
into your shell and then, once that has installed, type errno 2
. You can also use errno -l
for all error numbers, or see only the file ones by piping it to grep
, like this: errno -l | grep file
.
[edit based on this now being possible in recent versions]
[Updated Answer] You can query the following way to get back the name of class and the student id only if they are already enrolled.
db.student.find({},
{_id:0, name:1, students:{$elemMatch:{$eq:ObjectId("51780f796ec4051a536015cf")}}})
and you will get back what you expected:
{ "name" : "CS 101", "students" : [ ObjectId("51780f796ec4051a536015cf") ] }
{ "name" : "Literature" }
{ "name" : "Physics", "students" : [ ObjectId("51780f796ec4051a536015cf") ] }
[Original Answer] It's not possible to do what you want to do currently. This is unfortunate because you would be able to do this if the student was stored in the array as an object. In fact, I'm a little surprised you are using just ObjectId() as that will always require you to look up the students if you want to display a list of students enrolled in a particular course (look up list of Id's first then look up names in the students collection - two queries instead of one!)
If you were storing (as an example) an Id and name in the course array like this:
{
"_id" : ObjectId("51780fb5c9c41825e3e21fc6"),
"name" : "Physics",
"students" : [
{id: ObjectId("51780f796ec4051a536015cf"), name: "John"},
{id: ObjectId("51780f796ec4051a536015d0"), name: "Sam"}
]
}
Your query then would simply be:
db.course.find( { },
{ students :
{ $elemMatch :
{ id : ObjectId("51780f796ec4051a536015d0"),
name : "Sam"
}
}
}
);
If that student was only enrolled in CS 101 you'd get back:
{ "name" : "Literature" }
{ "name" : "Physics" }
{
"name" : "CS 101",
"students" : [
{
"id" : ObjectId("51780f796ec4051a536015cf"),
"name" : "John"
}
]
}
Starting with the following sample data :
df <- data.frame(v1=letters[1:5],v2=1:5,v3=letters[10:14],stringsAsFactors=FALSE)
v1 v2 v3
1 a 1 j
2 b 2 k
3 c 3 l
4 d 4 m
5 e 5 n
You can use :
data.frame(lapply(df, function(v) {
if (is.character(v)) return(toupper(v))
else return(v)
}))
Which gives :
v1 v2 v3
1 A 1 J
2 B 2 K
3 C 3 L
4 D 4 M
5 E 5 N
From the Python glossary:
It’s important to keep in mind that all packages are modules, but not all modules are packages. Or put another way, packages are just a special kind of module. Specifically, any module that contains a
__path__
attribute is considered a package.
Python files with a dash in the name, like my-file.py
, cannot be imported with a simple import
statement. Code-wise, import my-file
is the same as import my - file
which will raise an exception. Such files are better characterized as scripts whereas importable files are modules.
Adding max-width: 100%;
to the img
tag works for me.
You can use in your vimrc
those commands:
set ignorecase
- All your searches will be case insensitiveset smartcase
- Your search will be case sensitive if it contains an uppercase letterYou need to set ignorecase
if you want to use what smartcase
provides.
I wrote recently an article about Vim search commands (both built in command and the best plugins to search efficiently).
i want to post my solution here which was done AngularJS, ASP.NET MVC. The code illustrates how to download file with authentication.
WebApi method along with helper class:
[RoutePrefix("filess")]
class FileController: ApiController
{
[HttpGet]
[Route("download-file")]
[Authorize(Roles = "admin")]
public HttpResponseMessage DownloadDocument([FromUri] int fileId)
{
var file = "someFile.docx"// asking storage service to get file path with id
return Request.ReturnFile(file);
}
}
static class DownloadFIleFromServerHelper
{
public static HttpResponseMessage ReturnFile(this HttpRequestMessage request, string file)
{
var result = request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(new FileStream(file, FileMode.Open, FileAccess.Read));
result.Content.Headers.Add("x-filename", Path.GetFileName(file)); // letters of header names will be lowercased anyway in JS.
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = Path.GetFileName(file)
};
return result;
}
}
Web.config file changes to allow sending file name in custom header.
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Methods" value="POST,GET,PUT,PATCH,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Authorization,Content-Type,x-filename" />
<add name="Access-Control-Expose-Headers" value="Authorization,Content-Type,x-filename" />
<add name="Access-Control-Allow-Origin" value="*" />
Angular JS Service Part:
function proposalService($http, $cookies, config, FileSaver) {
return {
downloadDocument: downloadDocument
};
function downloadFile(documentId, errorCallback) {
$http({
url: config.apiUrl + "files/download-file?documentId=" + documentId,
method: "GET",
headers: {
"Content-type": "application/json; charset=utf-8",
"Authorization": "Bearer " + $cookies.get("api_key")
},
responseType: "arraybuffer"
})
.success( function(data, status, headers) {
var filename = headers()['x-filename'];
var blob = new Blob([data], { type: "application/octet-binary" });
FileSaver.saveAs(blob, filename);
})
.error(function(data, status) {
console.log("Request failed with status: " + status);
errorCallback(data, status);
});
};
};
Module dependency for FileUpload: angular-file-download (gulp install angular-file-download --save). Registration looks like below.
var app = angular.module('cool',
[
...
require('angular-file-saver'),
])
. // other staff.
Use a SortedSet (TreeSet is the default one):
SortedSet<String> set=new TreeSet<String>();
set.add("12");
set.add("15");
set.add("5");
List<String> list=new ArrayList<String>(set);
No extra sorting code needed.
Oh, I see you want a different sort order. Supply a Comparator to the TreeSet:
new TreeSet<String>(Comparator.comparing(Integer::valueOf));
Now your TreeSet will sort Strings in numeric order (which implies that it will throw exceptions if you supply non-numeric strings)
Reference:
TreeSet
Comparator
\n
won't work if you're inside java code though:
<% System.out.print("<script>alert('Some \n text')</script>"); %>
I know its not an answer, just thought it was important.
There is nothing like a "JSON object" - JSON is a serialization notation.
If you want to transform your javascript object to a javascript array, either you write your own loop [which would not be that complex!], or you rely on underscore.js _.toArray()
method:
var obj = {"0":"1","1":"2","2":"3","3":"4"};
var yourArray = _(obj).toArray();
If you use IIS Express via Visual Studio instead of the builtin ASP.net host, you can achieve this.
Enter this line into Hive command line interface:
insert overwrite directory '/data/test' row format delimited fields terminated by '\t' stored as textfile select * from testViewQuery;
testViewQuery
- some specific view
You can try it out http://api.jquery.com/mouseover/ on the jQuery doc page. It's a nice little, interactive demo that makes it very clear and you can actually see for yourself.
In short, you'll notice that a mouse over event occurs on an element when you are over it - coming from either its child OR parent element, but a mouse enter event only occurs when the mouse moves from the parent element to the element.
It sounds like you are debugging an optimised / release build, despite having the optimised box un-checked. Things you can try are:
If you cant't see the Modules menu item in the Debug -> Windows menu then you may need to add it in the "Customise..." menu.
It don't create normally; you need to add it by yourself.
After adding Global.asax
by
You need to add a class
Inherit the newly generated by System.Web.HttpApplication
and copy all the method created Global.asax
to Global.cs
and also add an inherit attribute to the Global.asax file.
Your Global.asax will look like this: -
<%@ Application Language="C#" Inherits="Global" %>
Your Global.cs in App_Code
will look like this: -
public class Global : System.Web.HttpApplication
{
public Global()
{
//
// TODO: Add constructor logic here
//
}
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
/// Many other events like begin request...e.t.c, e.t.c
}
You can make a union using .addAll(), and an intersection using .retainAll(), of the two sets and use .removeIf(), to remove the intersection (or the duplicated element) from the union.
HashSet union = new HashSet(group1);
union.addAll(group2);
System.out.println("Union: " + union);
HashSet intersection = new HashSet(group1);
intersection.retainAll(group2);
System.out.println("Intersection: " + intersection);
HashSet difference = new HashSet(union);
difference.removeIf(n -> (difference.contains(intersection)));
System.out.println("Difference: " + difference);
This was asked on the www-style list, and Tab Atkins (spec editor) provided an answer explaining why. I'll elaborate on that a bit here.
To start out, let's initially assume our flex container is single-line (flex-wrap: nowrap
). In this case, there's clearly an alignment difference between the main axis and the cross axis -- there are multiple items stacked in the main axis, but only one item stacked in the cross axis. So it makes sense to have a customizeable-per-item "align-self" in the cross axis (since each item is aligned separately, on its own), whereas it doesn't make sense in the main axis (since there, the items are aligned collectively).
For multi-line flexbox, the same logic applies to each "flex line". In a given line, items are aligned individually in the cross axis (since there's only one item per line, in the cross axis), vs. collectively in the main axis.
Here's another way of phrasing it: so, all of the *-self
and *-content
properties are about how to distribute extra space around things. But the key difference is that the *-self
versions are for cases where there's only a single thing in that axis, and the *-content
versions are for when there are potentially many things in that axis. The one-thing vs. many-things scenarios are different types of problems, and so they have different types of options available -- for example, the space-around
/ space-between
values make sense for *-content
, but not for *-self
.
SO: In a flexbox's main axis, there are many things to distribute space around. So a *-content
property makes sense there, but not a *-self
property.
In contrast, in the cross axis, we have both a *-self
and a *-content
property. One determines how we'll distribute space around the many flex lines (align-content
), whereas the other (align-self
) determines how to distribute space around individual flex items in the cross axis, within a given flex line.
(I'm ignoring *-items
properties here, since they simply establish defaults for *-self
.)
--- create a ws server vs2012 upd 3
new project
choose .net framework 3.5
asp.net web service application
right click on the project root
choose add service reference
choose wsdl
--- how can I create a ws client from a wsdl file?
I´ve a ws server Axis2 under tomcat 7 and I want to test the compatibility
CREATE DATABASE hindi_test
CHARACTER SET utf8
COLLATE utf8_unicode_ci;
USE hindi_test;
CREATE TABLE `hindi` (`data` varchar(200) COLLATE utf8_unicode_ci NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `hindi` (`data`) VALUES('????????');
Like this
DECLARE @date DATETIME
SET @date = '2011-09-28 18:01:00'
select convert(varchar, @date,105) + ' ' + convert(varchar, @date,108)
Firstly, you should check if your image column is BLOB type!
I don't know anything about your SQL table, but if I'll try to make my own as an example.
We got fields id
(int), image
(blob) and image_name
(varchar(64)).
So the code should look like this (assume ID is always '1' and let's use this mysql_query):
$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); //SQL Injection defence!
$image_name = addslashes($_FILES['image']['name']);
$sql = "INSERT INTO `product_images` (`id`, `image`, `image_name`) VALUES ('1', '{$image}', '{$image_name}')";
if (!mysql_query($sql)) { // Error handling
echo "Something went wrong! :(";
}
You are doing it wrong in many ways. Don't use mysql functions - they are deprecated! Use PDO or MySQLi. You should also think about storing files locations on disk. Using MySQL for storing images is thought to be Bad Idea™. Handling SQL table with big data like images can be problematic.
Also your HTML form is out of standards. It should look like this:
<form action="insert_product.php" method="POST" enctype="multipart/form-data">
<label>File: </label><input type="file" name="image" />
<input type="submit" />
</form>
Sidenote:
When dealing with files and storing them as a BLOB, the data must be escaped using mysql_real_escape_string()
, otherwise it will result in a syntax error.
In a bash-like environment you can use:
keytool -list -v -keystore cacerts.jks | grep 'Alias name:' | grep -i foo
This command consist of 3 parts. As stated above, the 1st part will list all trusted certificates with all the details and that's why the 2nd part comes to filter only the alias information among those details. And finally in the 3rd part you can search for a specific alias (or part of it). The -i turns the case insensitive mode on. Thus the given command will yield all aliases containing the pattern 'foo', f.e. foo, 123_FOO, fooBar, etc. For more information man grep
.
just remove float: left
and replace align with margin: 0 auto
and it will be centered.
Thread thread = new Thread(Work);
thread.Start(Parameter);
private void Work(object param)
{
string Parameter = (string)param;
}
The parameter type must be an object.
EDIT:
While this answer isn't incorrect I do recommend against this approach. Using a lambda expression is much easier to read and doesn't require type casting. See here: https://stackoverflow.com/a/1195915/52551
I'm running version 1.21, but I think this may apply to earlier versions as well.
Take a look at the bottom right-hand side of the screen. You should see something that says Spaces
or Tab-Size
.
Mine shows spaces, →
This only works per document, not project-wide. If you want to apply it project-wide, you need to also add "editor.detectIndentation": false
to your user settings.
How about creating two dataframes, each with different data types for their columns, and then appending them together?
d1 = pd.DataFrame(columns=[ 'float_column' ], dtype=float)
d1 = d1.append(pd.DataFrame(columns=[ 'string_column' ], dtype=str))
Results
In[8}: d1.dtypes
Out[8]:
float_column float64
string_column object
dtype: object
After the dataframe is created, you can populate it with floating point variables in the 1st column, and strings (or any data type you desire) in the 2nd column.
To Remove Special character
String t2 = "!@#$%^&*()-';,./?><+abdd";
t2 = t2.replaceAll("\\W+","");
Output will be : abdd.
This works perfectly.
Along with what Jonathan and Samir suggested (both excellent answers btw!), jQuery has some built in events that it'll fire for you when making an ajax request.
There's the ajaxStart
event
Show a loading message whenever an AJAX request starts (and none is already active).
...and it's brother, the ajaxStop
event
Attach a function to be executed whenever all AJAX requests have ended. This is an Ajax Event.
Together, they make a fine way to show a progress message when any ajax activity is happening anywhere on the page.
HTML:
<div id="loading">
<p><img src="loading.gif" /> Please Wait</p>
</div>
Script:
$(document).ajaxStart(function(){
$('#loading').show();
}).ajaxStop(function(){
$('#loading').hide();
});
Element.children
returns only element children, while Node.childNodes
returns all node children. Note that elements are nodes, so both are available on elements.
I believe childNodes
is more reliable. For example, MDC (linked above) notes that IE only got children
right in IE 9. childNodes
provides less room for error by browser implementors.
Another solution that it is similar to those already exposed here is this one. Just before the closing body tag place this html:
<div id="resultLoading" style="display: none; width: 100%; height: 100%; position: fixed; z-index: 10000; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto;">
<div style="width: 340px; height: 200px; text-align: center; position: fixed; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto; z-index: 10; color: rgb(255, 255, 255);">
<div class="uil-default-css">
<img src="/images/loading-animation1.gif" style="max-width: 150px; max-height: 150px; display: block; margin-left: auto; margin-right: auto;" />
</div>
<div class="loader-text" style="display: block; font-size: 18px; font-weight: 300;"> </div>
</div>
<div style="background: rgb(0, 0, 0); opacity: 0.6; width: 100%; height: 100%; position: absolute; top: 0px;"></div>
</div>
Finally, replace .loader-text element's
content on the fly on every navigation event and turn on the #resultloading
div, note that it is initially hidden.
var showLoader = function (text) {
$('#resultLoading').show();
$('#resultLoading').find('.loader-text').html(text);
};
jQuery(document).ready(function () {
jQuery(window).on("beforeunload ", function () {
showLoader('Loading, please wait...');
});
});
This can be applied to any html based project with jQuery where you don't know which pages of your administration area will take too long to finish loading.
The gif image is 176x176px but you can use any transparent gif animation, please take into account that the image size is not important as it will be maxed to 150x150px.
Also, the function showLoader can be called on an element's click to perform an action that will further redirect the page, that is why it is provided ad an individual function. i hope this can also help anyone.
You can use the rather sensibly named xpath function called concat here
<a>
<xsl:attribute name="href">
<xsl:value-of select="concat('myText:', /*/properties/property[@name='report']/@value)" />
</xsl:attribute>
</a>
Of course, it doesn't have to be text here, it can be another xpath expression to select an element or attribute. And you can have any number of arguments in the concat expression.
Do note, you can make use of Attribute Value Templates (represented by the curly braces) here to simplify your expression
<a href="{concat('myText:', /*/properties/property[@name='report']/@value)}"></a>
I'm not sure @cmbuckley answer is showing the full picture. What I read is:
Unless the cookie's attributes indicate otherwise, the cookie is returned only to the origin server (and not, for example, to any subdomains), and it expires at the end of the current session (as defined by the user agent). User agents ignore unrecognized cookie.
Also
8.6. Weak Integrity
Cookies do not provide integrity guarantees for sibling domains (and
their subdomains). For example, consider foo.example.com and
bar.example.com. The foo.example.com server can set a cookie with a
Domain attribute of "example.com" (possibly overwriting an existing
"example.com" cookie set by bar.example.com), and the user agent will
include that cookie in HTTP requests to bar.example.com. In the
worst case, bar.example.com will be unable to distinguish this cookie
from a cookie it set itself. The foo.example.com server might be
able to leverage this ability to mount an attack against
bar.example.com.
To me that means you can protect cookies from being read by subdomain/domain but cannot prevent writing cookies to the other domains. So somebody may rewrite your site cookies by controlling another subdomain visited by the same browser. Which might not be a big concern.
Awesome cookies test site provided by @cmbuckley /for those that missed it in his answer like me; worth scrolling up and upvoting/:
According to the documentation, just like with any css selector, you can specify as many conditions as you want, and they are treated as logical 'OR'.
This example returns a list of all div elements within the document with a class of either "note" or "alert":
var matches = document.querySelectorAll("div.note, div.alert");
source: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
Meanwhile to get the 'AND' functionality you can for example simply use a multiattribute selector, as jquery says:
https://api.jquery.com/multiple-attribute-selector/
ex. "input[id][name$='man']"
specifies both id and name of the element and both conditions must be met. For classes it's as obvious as ".class1.class2
" to require object of 2 classes.
All possible combinations of both are valid, so you can easily get equivalent of more sophisticated 'OR' and 'AND' expressions.
If key
isn't an int
or float
but a str
ing, you need to convert it to an int
first by doing
key = int(key)
or to a float
by doing
key = float(key)
Otherwise, what you have in your question should work, but
if (key < 1) or (key > 34):
or
if not (1 <= key <= 34):
would be a bit clearer.
Found this on github...
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import pandas
Using OVER()
and LIMIT 1
:
SELECT COUNT(1) OVER()
FROM posts
INNER JOIN votes ON votes.post_id = posts.id
GROUP BY posts.id
LIMIT 1;
public static List<HtmlNode> GetTagsWithClass(string html,List<string> @class)
{
// LoadHtml(html);
var result = htmlDocument.DocumentNode.Descendants()
.Where(x =>x.Attributes.Contains("class") && @class.Contains(x.Attributes["class"].Value)).ToList();
return result;
}
An optimized version of the implementation of the reverse function proposed by @michieljoris (according to the comments of @Beterraba and @Mala):
function a2hex(str) {_x000D_
var hex = '';_x000D_
for (var i = 0, l = str.length; i < l; i++) {_x000D_
var hexx = Number(str.charCodeAt(i)).toString(16);_x000D_
hex += (hexx.length > 1 && hexx || '0' + hexx);_x000D_
}_x000D_
return hex;_x000D_
}_x000D_
alert(a2hex('2460')); // display 32343630
_x000D_
The easiest way would be using Substring
string str = "AM0122200204";
string substr = str.Substring(str.Length - 3);
Using the overload with one int
as I put would get the substring
of a string
, starting from the index int
. In your case being str.Length - 3
, since you want to get the last three chars.
better code that doesn't involve ping:
SET COUNTER=0
:loop
SET /a COUNTER=%COUNTER%+1
XCOPY "Server\*" "c:\minecraft\backups\server_backup_%COUNTER%" /i /s
timeout /t 600 /nobreak >nul
goto loop
600 seconds is 10 minutes, however you can set it whatever time you'd like
The settings for Decimal
are its precision and scale or in normal language, how many digits can a number have and how many digits do you want to have to the right of the decimal point.
So if you put PI
into a Decimal(18,0)
it will be recorded as 3
?
If you put PI
into a Decimal(18,2)
it will be recorded as 3.14
?
If you put PI
into Decimal(18,10)
be recorded as 3.1415926535
.
I can't comment yet, but make sure you made all the checks in this quide: How to enable remote connections in SQL Server 2008? It should work fine if all steps are made.
If you use Java and spring MVC you just need to add the following annotation to your method returning your page :
@CrossOrigin(origins = "*")
"*" is to allow your page to be accessible from anywhere. See https://developer.mozilla.org/fr/docs/Web/HTTP/Headers/Access-Control-Allow-Origin for more details about that.
I know that its bit old Q but if u get here by searching a solution so i got a nice one via jquery
jQuery('a[target^="_new"]').click(function() {
var width = window.innerWidth * 0.66 ;
// define the height in
var height = width * window.innerHeight / window.innerWidth ;
// Ratio the hight to the width as the user screen ratio
window.open(this.href , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));
});
it will open all the <a target="_new">
in a new window
EDIT:
1st, I did some little changes in the original code now it open the new window perfectly followed the user screen ratio (for landscape desktops)
but, I would like to recommend you to use the following code that open the link in new tab if you in mobile (thanks to zvona answer in other question):
jQuery('a[target^="_new"]').click(function() {
return openWindow(this.href);
}
function openWindow(url) {
if (window.innerWidth <= 640) {
// if width is smaller then 640px, create a temporary a elm that will open the link in new tab
var a = document.createElement('a');
a.setAttribute("href", url);
a.setAttribute("target", "_blank");
var dispatch = document.createEvent("HTMLEvents");
dispatch.initEvent("click", true, true);
a.dispatchEvent(dispatch);
}
else {
var width = window.innerWidth * 0.66 ;
// define the height in
var height = width * window.innerHeight / window.innerWidth ;
// Ratio the hight to the width as the user screen ratio
window.open(url , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));
}
return false;
}
Actually I tried creating empty stdClass and compared the speed to empty class.
class emp{}
then proceeded creating 1000 stdClasses and emps... empty classes were done in around 1100 microseconds while stdClasses took over 1700 microseconds. So I guess its better to create your own dummy class for storing data if you want to use objects for that so badly (arrays are a lot faster for both writing and reading).
I didn't use regex since it is difficult to deal with nested code. So this snippet should be able to allow you to grab sections of code with balanced brackets:
def extract_code(data):
""" returns an array of code snippets from a string (data)"""
start_pos = None
end_pos = None
count_open = 0
count_close = 0
code_snippets = []
for i,v in enumerate(data):
if v =='{':
count_open+=1
if not start_pos:
start_pos= i
if v=='}':
count_close +=1
if count_open == count_close and not end_pos:
end_pos = i+1
if start_pos and end_pos:
code_snippets.append((start_pos,end_pos))
start_pos = None
end_pos = None
return code_snippets
I used this to extract code snippets from a text file.
Use android image without PlayServices then you'll be able to run add root and access whatever you want.
Further to @Udi post this is what the script tried to do, but did not work with me.
I had to the set the following in the PATH
nothing else.
C:\Users\hUTBER\AppData\Local\Programs\Python\Python35
C:\Users\hUTBER\AppData\Local\Programs\Python\Python35\Scripts
Were mine and now python
works in the cmd
If you want them to show up one at a time, you can do this:
import time
import sys
for i in range(20):
sys.stdout.write('a')
sys.stdout.flush()
time.sleep(0.5)
sys.stdout.flush()
is necessary to force the character to be written each time the loop is run.
Attention Android Wear developers: "Remove Unused Resources" will delete the xml file where you declare the capability name (res/values/wear.xml) and the phone won't be able to connect to the watch. I spent hours trying to figure out this bug in my app.
best way to Round off number to decimal places is that
a=parseFloat(Math.round(numbertobeRound*10^decimalplaces)/10^decimalplaces);
for Example ;
numbertobeRound=58.8965896589;
if you want 58.90
decimalplaces is 2
a=parseFloat(Math.round(58.8965896589*10^2)/10^2);
Note that if your canvas is statically declared you should use the width
and height
attributes, not the style, eg. this will work:
<canvas id="c" height="100" width="100" style="border:1px"></canvas>
<script>
document.getElementById('c').width = 200;
</script>
But this will not work:
<canvas id="c" style="width: 100px; height: 100px; border:1px"></canvas>
<script>
document.getElementById('c').width = 200;
</script>
A single bracket ([
) usually actually calls a program named [
; man test
or man [
for more info. Example:
$ VARIABLE=abcdef
$ if [ $VARIABLE == abcdef ] ; then echo yes ; else echo no ; fi
yes
The double bracket ([[
) does the same thing (basically) as a single bracket, but is a bash builtin.
$ VARIABLE=abcdef
$ if [[ $VARIABLE == 123456 ]] ; then echo yes ; else echo no ; fi
no
Parentheses (()
) are used to create a subshell. For example:
$ pwd
/home/user
$ (cd /tmp; pwd)
/tmp
$ pwd
/home/user
As you can see, the subshell allowed you to perform operations without affecting the environment of the current shell.
(a) Braces ({}
) are used to unambiguously identify variables. Example:
$ VARIABLE=abcdef
$ echo Variable: $VARIABLE
Variable: abcdef
$ echo Variable: $VARIABLE123456
Variable:
$ echo Variable: ${VARIABLE}123456
Variable: abcdef123456
(b) Braces are also used to execute a sequence of commands in the current shell context, e.g.
$ { date; top -b -n1 | head ; } >logfile
# 'date' and 'top' output are concatenated,
# could be useful sometimes to hunt for a top loader )
$ { date; make 2>&1; date; } | tee logfile
# now we can calculate the duration of a build from the logfile
There is a subtle syntactic difference with ( )
, though (see bash reference) ; essentially, a semicolon ;
after the last command within braces is a must, and the braces {
, }
must be surrounded by spaces.
awk '$3 ~ /snow/ { print }' dummy_file
Add a class of 'disablecopypaste' to the inputs you want to disable the copy paste functionality on and add this jQuery script
$(document).ready(function () {
$('input.disablecopypaste').bind('copy paste', function (e) {
e.preventDefault();
});
});
I've got a pretty simple yet smart workaround: Just define the array with variables in its name. For example:
for (( i=0 ; i<$(($maxvalue + 1)) ; i++ ))
do
for (( j=0 ; j<$(($maxargument + 1)) ; j++ ))
do
declare -a array$i[$j]=((Your rule))
done
done
Don't know whether this helps since it's not exactly what you asked for, but it works for me. (The same could be achieved just with variables without the array)
I use a custom style
<style name="MyButtonStyle" parent="@style/Widget.AppCompat.Button.Borderless"></style>
Don't forget to add
<item name="android:textAllCaps">false</item>
otherwise the button text will be in UpperCase.
the above all look good
but do you want to keep the result?
if so...
you can use the following
result = [element for element in data if element[1] == search]
then a simple
len(result)
lets you know if anything was found (and now you can do stuff with the results)
of course this does not handle elements which are length less than one (which you should be checking unless you know they always are greater than length 1, and in that case should you be using a tuple? (tuples are immutable))
if you know all items are a set length you can also do:
any(second == search for _, second in data)
or for len(data[0]) == 4:
any(second == search for _, second, _, _ in data)
...and I would recommend using
for element in data:
...
instead of
for i in range(len(data)):
...
(for future uses, unless you want to save or use 'i', and just so you know the '0' is not required, you only need use the full syntax if you are starting at a non zero value)
Console.Read()
basically reads a character so if you are on a console and you press a key then the console will close, meanwhile Console.Readline()
will read the whole string.
if you need the index just use:
import random
foo = ['a', 'b', 'c', 'd', 'e']
print int(random.random() * len(foo))
print foo[int(random.random() * len(foo))]
random.choice does the same:)
I found this post trying to figure why I kept getting the following error which is explained by the other answers.
The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
Use a nullable DateTime object.
public DateTime? PurchaseDate { get; set; }
If you are using entity framework Set the nullable property in the edmx file to True
I was testing my application with the Android emulator and I solved this by turning off and turning on the Wi-Fi on the Android emulator device! It worked perfectly.
Use the is_user_logged_in
function:
if ( is_user_logged_in() ) {
// your code for logged in user
} else {
// your code for logged out user
}
Finally, I found the solution to my problem.
I looked into the Magento system log file (var/log/system.log). There I saw the exact error.
The error is as below:-
Recoverable Error: Argument 1 passed to Mage_Core_Model_Store::setWebsite() must be an instance of Mage_Core_Model_Website, null given, called in YOUR_PATH\app\code\core\Mage\Core\Model\App.php on line 555 and defined in YOUR_PATH\app\code\core\Mage\Core\Model\Store.php on line 285
Recoverable Error: Argument 1 passed to Mage_Core_Model_Store_Group::setWebsite() must be an instance of Mage_Core_Model_Website, null given, called in YOUR_PATH\app\code\core\Mage\Core\Model\App.php on line 575 and defined in YOUR_PATH\app\code\core\Mage\Core\Model\Store\Group.php on line 227
Actually, I had this error before. But, error display message like Error: 404 Not Found
was new to me.
The reason for this error is that store_id
and website_id
for admin should be set to 0 (zero). But, when you import database to new server, somehow these values are not set to 0.
Open PhpMyAdmin and run the following query in your database:-
SET FOREIGN_KEY_CHECKS=0;
UPDATE `core_store` SET store_id = 0 WHERE code='admin';
UPDATE `core_store_group` SET group_id = 0 WHERE name='Default';
UPDATE `core_website` SET website_id = 0 WHERE code='admin';
UPDATE `customer_group` SET customer_group_id = 0 WHERE customer_group_code='NOT LOGGED IN';
SET FOREIGN_KEY_CHECKS=1;
I have written about this problem and solution over here:-
Magento: Solution to "Error: 404 Not Found" in Admin Login Page
You should follow the Google guide;
ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
} else {
// The toggle is disabled
}
}
});
You can check the documentation here
Complete howto in the perfaq here: http://learn.perl.org/faq/perlfaq4.html#How-do-I-strip-blank-space-from-the-beginning-end-of-a-string-
What you wrote would get you the greatest id
assuming they were unique and auto-incremented that would be fine assuming you are okay with inviting concurrency issues.
Since you're using MySQL as your database, there is the specific function LAST_INSERT_ID()
which only works on the current connection that did the insert.
PHP offers a specific function for that too called mysql_insert_id
.
It is not that truncate does not log anything in SQL Server. truncate does not log any information but it log the deallocation of data page for the table on which you fired TRUNCATE.
and truncated record can be rollback if we define transaction at beginning and we can recover the truncated record after rollback it. But can not recover truncated records from the transaction log backup after committed truncated transaction.
Here is a helper function to perform a simple Cartesian product with two data frames. The internal logic handles using an internal key, and avoids mangling any columns that happen to be named "key" from either side.
import pandas as pd
def cartesian(df1, df2):
"""Determine Cartesian product of two data frames."""
key = 'key'
while key in df1.columns or key in df2.columns:
key = '_' + key
key_d = {key: 0}
return pd.merge(
df1.assign(**key_d), df2.assign(**key_d), on=key).drop(key, axis=1)
# Two data frames, where the first happens to have a 'key' column
df1 = pd.DataFrame({'number':[1, 2], 'key':[3, 4]})
df2 = pd.DataFrame({'digit': [5, 6]})
cartesian(df1, df2)
shows:
number key digit
0 1 3 5
1 1 3 6
2 2 4 5
3 2 4 6
I eventually stumbled upon an example of the usage I was looking for - to assign an error to the Model in general, rather than one of it's properties, as usual you call:
ModelState.AddModelError(string key, string errorMessage);
but use an empty string for the key:
ModelState.AddModelError(string.Empty, "There is something wrong with Foo.");
The error message will present itself in the <%: Html.ValidationSummary() %>
as you'd expect.
The Unix Date command will display in epoch time
the command is
date +"%s"
https://linux.die.net/man/1/date
Edit: Some people have observed you asked for days, so it's the result of that command divided by 86,400
Here you go:
<?php
$html = '<p style="border: 1px solid red;">Test</p>';
echo preg_replace('/<p style="(.+?)">(.+?)<\/p>/i', "<p>$2</p>", $html);
?>
By the way, as pointed out by others, regex are not suggested for this.
I guess this is what you want, it does exactly what you specified.
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char** argv) {
int age;
char* buffer;
buffer = malloc(200 * sizeof(char));
sscanf("19 cool kid", "%d cool %s", &age, buffer);
printf("cool %s is %d years old\n", buffer, age);
return 0;
}
The format expects: first a number (and puts it at where &age points to), then whitespace (zero or more), then the literal string "cool", then whitespace (zero or more) again, and then finally a string (and put that at whatever buffer points to). You forgot the "cool" part in your format string, so the format then just assumes that is the string you were wanting to assign to buffer. But you don't want to assign that string, only skip it.
Alternative, you could also have a format string like: "%d %s %s", but then you must assign another buffer for it (with a different name), and print it as: "%s %s is %d years old\n".
{ }
-->
defines scope, so if(a==1) { int b = 10; }
says, you are defining int b, for {}- this scope. For
if(a==1)
int b =10;
there is no scope. And you will not be able to use b
anywhere.
Another cause of this can be including a header that depends on windows.h
, before including windows.h
.
In my case I included xinput.h
before windows.h
and got this error. Swapping the order solved the problem.
Try this:
Alex Misuno@hp4530s ~
$ cat test.txt
1 OK
2 OK
3 NOTOK
4 OK
5 NOTOK
Alex Misuno@hp4530s ~
$ cat test.txt | grep ".* OK$"
1 OK
2 OK
4 OK
Update 2019 - Bootstrap 4.0.0
The pull-right
class is now float-right
in Bootstrap 4...
<div class="row">
<div class="col-12">One <input type="button" class="btn float-right" value="test"></div>
<div class="col-12">Two <input type="button" class="btn float-right" value="test"></div>
</div>
http://www.codeply.com/go/nTobetXAwb
It's also better to not align the ul list and use block elements for the rows.
Is float-right
still not working?
Remember that Bootstrap 4 is now flexbox, and many elements are display:flex
which can prevent float-right from working. In some cases, the util classes like align-self-end
or ml-auto
work to right align elements that are inside a flexbox container like a Bootstrap 4 .row, Card or Nav.
Also remember that text-right
still works on inline elements.
Bootstrap 4 align right examples
Bootstrap 3
Use the pull-right
class.
My implementation:
def get_nested(data, *args):
if args and data:
element = args[0]
if element:
value = data.get(element)
return value if len(args) == 1 else get_nested(value, *args[1:])
Example usage:
>>> dct={"foo":{"bar":{"one":1, "two":2}, "misc":[1,2,3]}, "foo2":123}
>>> get_nested(dct, "foo", "bar", "one")
1
>>> get_nested(dct, "foo", "bar", "two")
2
>>> get_nested(dct, "foo", "misc")
[1, 2, 3]
>>> get_nested(dct, "foo", "missing")
>>>
There are no exceptions raised in case a key is missing, None value is returned in that case.
You have to find the right user that needs to use temp folder. In my computer I follow the above link and find the special folder c:\inetpub, that iis use to execute her web services. I check what users could use these folder and find something like these: computername\iis_isusrs
The main issue comes when you try to add it to all permit on temp folder I was going to properties, security tab, edit button, add user button then i put iis_isusrs
and "check names" button
It doesn´t find anything The reason is the in my case it looks ( windows 2008 r2 iis 7 ) on pdgs.local location You have to go to "Select Users or Groups" form, click on Advanced button, click on Locations button and will see a specific hierarchy
So when you try to add an user, its search name on pdgs.local. You have to select computername and click ok, Click on "Find Now"
Look for IIS_IUSRS on Name(RDN) column, click ok. So we go back to "Select Users or Groups" form with new and right user underline
click ok, allow full control, and click ok again.
That´s all folks, Hope it helps,
Jose from Moralzarzal ( Madrid )
public class ApiClient {
private static Retrofit retrofit = null;
private static final Object LOCK = new Object();
public static void clear() {
synchronized (LOCK) {
retrofit = null;
}
}
public static Retrofit getClient() {
synchronized (LOCK) {
if (retrofit == null) {
Gson gson = new GsonBuilder()
.setLenient()
.create();
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.connectTimeout(40, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build();
retrofit = new Retrofit.Builder()
.client(okHttpClient)
.baseUrl(Constants.WEB_SERVICE)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit;
}
}
public static RequestBody plain(String content) {
return getRequestBody("text/plain", content);
}
public static RequestBody getRequestBody(String type, String content) {
return RequestBody.create(MediaType.parse(type), content);
}
}
@FormUrlEncoded
@POST("architect/project_list_Design_files")
Call<DesignListModel> getProjectDesign(
@Field("project_id") String project_id);
@Multipart
@POST("architect/upload_design")
Call<BoqListModel> getUpLoadDesign(
@Part("user_id") RequestBody user_id,
@Part("request_id") RequestBody request_id,
@Part List<MultipartBody.Part> image_file,
@Part List<MultipartBody.Part> design_upload_doc);
private void getMyProjectList()
{
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<MyProjectListModel> call = apiService.getMyProjectList("",Sorting,latitude,longitude,Search,Offset+"",Limit);
call.enqueue(new Callback<MyProjectListModel>() {
@Override
public void onResponse(Call<MyProjectListModel> call, Response<MyProjectListModel> response) {
try {
Log.e("response",response.body()+"");
} catch (Exception e)
{
Log.e("onResponse: ", e.toString());
}
}
@Override
public void onFailure(Call<MyProjectListModel> call, Throwable t)
{
Log.e( "onFailure: ",t.toString());
}
});
}
// file upload
private void getUpload(String path,String id)
{
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
MultipartBody.Part GalleryImage = null;
if (path!="")
{
File file = new File(path);
RequestBody reqFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
GalleryImage = MultipartBody.Part.createFormData("image", file.getName(), reqFile);
}
RequestBody UserId = RequestBody.create(MediaType.parse("text/plain"), id);
Call<uplod_file> call = apiService.geUplodFileCall(UserId,GalleryImage);
call.enqueue(new Callback<uplod_file>() {
@Override
public void onResponse(Call<uplod_file> call, Response<uplod_file> response) {
try {
Log.e("response",response.body()+"");
Toast.makeText(getApplicationContext(),response.body().getMessage(),Toast.LENGTH_SHORT).show();
} catch (Exception e)
{
Log.e("onResponse: ", e.toString());
}
}
@Override
public void onFailure(Call<uplod_file> call, Throwable t)
{
Log.e( "onFailure: ",t.toString());
}
});
}
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
You can try
#include <iostream>
#include <conio.h>
int main() {
//some codes
getch();
return 0;
}
It depends, you can use jQuery to adjust the ranges proportionally I think. Why do you use an image map by the way? Can't you use scaling divs or other elements for it?
Remove the '#' and do
Color c = Color.FromArgb(int.Parse("#FFFFFF".Replace("#",""),
System.Globalization.NumberStyles.AllowHexSpecifier));
Official documentation says, click on a link in a WebView will launch application that handles URLs. You need to override this default behavior
myWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
or if there is no conditional logic in the method simply do this
myWebView.setWebViewClient(new WebViewClient());
extension Array {
public func toDictionary<Key: Hashable>(with selectKey: (Element) -> Key) -> [Key:Element] {
var dict = [Key:Element]()
for element in self {
dict[selectKey(element)] = element
}
return dict
}
}
Public Sub ArrayDelAt(ByRef x As Array, ByVal stack As Integer)
For i = 0 To x.Length - 2
If i >= stack Then
x(i) = x(i + 1)
x(x.Length-1) = Nothing
End If
Next
End Sub
try this
it also can be a great idea using concat for EL + MAP + JSON problem like in this example :
#{myMap[''.concat(myid)].content}
Use mx-auto
in your div class using Bootstrap 4.
<div class="container">
<div class="row">
<div class="mx-auto">
You content here
</div>
</div>
</div>
I was struggling with this for a few days until I chanced on the issue when I had to build a new Dropdown. I had several DropDownList controls and attempted to get validation working with no luck. One was databound and the other was filled from the aspx page. I needed to drop the databound one and add a second manual list. In my case Validators failed if you built a dropdown like this and looked at any value (0 or -1) for either a required or compare validator:
<asp:DropDownList ID="DDL_Reason" CssClass="inputDropDown" runat="server">
<asp:ListItem>--Select--</asp:ListItem>
<asp:ListItem>Expired</asp:ListItem>
<asp:ListItem>Lost/Stolen</asp:ListItem>
<asp:ListItem>Location Change</asp:ListItem>
</asp:DropDownList>
However adding the InitialValue like this worked instantly for a compare Validator.
<asp:ListItem Text="-- Select --" Value="-1"></asp:ListItem>
The first parameter to the iterator in forEach
is the value and second is the key of the object.
angular.forEach(objectToIterate, function(value, key) {
/* do something for all key: value pairs */
});
In your example, the outer forEach is actually:
angular.forEach($scope.filters, function(filterObj , filterKey)
See my answer to a similar question here.
It sounds like you want a background-image to keep it's own aspect ratio while expanding to 100% width and getting cropped off on the top and bottom. If that's the case, do something like this:
.chapter {
position: relative;
height: 1200px;
z-index: 1;
}
#chapter1 {
background-image: url(http://omset.files.wordpress.com/2010/06/homer-simpson-1-264a0.jpg);
background-repeat: no-repeat;
background-size: 100% auto;
background-position: center top;
background-attachment: fixed;
}
jsfiddle: http://jsfiddle.net/ndKWN/3/
The problem with this approach is that you have the container elements at a fixed height, so there can be space below if the screen is small enough.
If you want the height to keep the image's aspect ratio, you'll have to do something like what I wrote in an edit to the answer I linked to above. Set the container's height
to 0 and set the padding-bottom
to the percentage of the width:
.chapter {
position: relative;
height: 0;
padding-bottom: 75%;
z-index: 1;
}
#chapter1 {
background-image: url(http://omset.files.wordpress.com/2010/06/homer-simpson-1-264a0.jpg);
background-repeat: no-repeat;
background-size: 100% auto;
background-position: center top;
background-attachment: fixed;
}
jsfiddle: http://jsfiddle.net/ndKWN/4/
You could also put the padding-bottom
percentage into each #chapter
style if each image has a different aspect ratio. In order to use different aspect ratios, divide the height of the original image by it's own width, and multiply by 100 to get the percentage value.
Try this:
delete from your_table;
delete from sqlite_sequence where name='your_table';
SQLite keeps track of the largest ROWID that a table has ever held using the special
SQLITE_SEQUENCE
table. TheSQLITE_SEQUENCE
table is created and initialized automatically whenever a normal table that contains an AUTOINCREMENT column is created. The content of the SQLITE_SEQUENCE table can be modified using ordinary UPDATE, INSERT, and DELETE statements. But making modifications to this table will likely perturb the AUTOINCREMENT key generation algorithm. Make sure you know what you are doing before you undertake such changes.
For future reference, you can get help for any command by using the /?
switch, which should explain what switches do what.
According to the set /?
screen, the format for set /p
is SET /P variable=[promptString]
which would indicate that the p in /p
is "prompt." It just prints in your example because <nul
passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.
/L
in for /L
generates a List of numbers.
From ping /?
:
Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
[-r count] [-s count] [[-j host-list] | [-k host-list]]
[-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name
Options:
-t Ping the specified host until stopped.
To see statistics and continue - type Control-Break;
To stop - type Control-C.
-a Resolve addresses to hostnames.
-n count Number of echo requests to send.
-l size Send buffer size.
-f Set Don't Fragment flag in packet (IPv4-only).
-i TTL Time To Live.
-v TOS Type Of Service (IPv4-only. This setting has been deprecated
and has no effect on the type of service field in the IP Header).
-r count Record route for count hops (IPv4-only).
-s count Timestamp for count hops (IPv4-only).
-j host-list Loose source route along host-list (IPv4-only).
-k host-list Strict source route along host-list (IPv4-only).
-w timeout Timeout in milliseconds to wait for each reply.
-R Use routing header to test reverse route also (IPv6-only).
-S srcaddr Source address to use.
-4 Force using IPv4.
-6 Force using IPv6.
Marking a controller's session state as readonly or disabled will solve the problem.
You can decorate a controller with the following attribute to mark it read-only:
[SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]
the System.Web.SessionState.SessionStateBehavior enum has the following values:
To quote:
Because map containers do not allow for duplicate key values, the insertion operation checks for each element inserted whether another element exists already in the container with the same key value, if so, the element is not inserted and its mapped value is not changed in any way.
So insert will not change the value if the key already exists, the [] operator
will.
EDIT:
This reminds me of another recent question - why use at()
instead of the [] operator
to retrieve values from a vector. Apparently at()
throws an exception if the index is out of bounds whereas [] operator
doesn't. In these situations it's always best to look up the documentation of the functions as they will give you all the details. But in general, there aren't (or at least shouldn't be) two functions/operators that do the exact same thing.
My guess is that, internally, insert()
will first check for the entry and afterwards itself use the [] operator
.
I think the best way to do this with basic R is:
for( i in rownames(df) )
print(df[i, "column1"])
The advantage over the for( i in 1:nrow(df))
-approach is that you do not get into trouble if df
is empty and nrow(df)=0
.
I solved this by running mvn -U install
from command line and then "Maven->Update Project" from Eclipse
.abc, .xyz { margin-left: 20px; }
is what you are looking for.
The code you pasted should work... There must be something else we are not seeing here.
Check this out. Working for me fine on IE7. When you submit you will see the variable passed in the URL.
Go to SQL command line:- type:
sql>connect / as sysdba;
then type:
sql>desc dba_users;
then type:
sql>select username,password from dba_users;
If sysdba
doesn't work then try connecting with username:scott and password: Tiger
You will be able to see all users with passwords. Probably you might find your's. Hope this helps
Use style. The font tag is deprecated (W3C Wiki).
you can do this with jdk >= 8
getComboBox().addItemListener(this::comboBoxitemStateChanged);
so
public void comboBoxitemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
YourObject selectedItem = (YourObject) e.getItem();
//TODO your actitons
}
}
Using query-string module is the recommended one when you need a module to parse your query string in ease.
componentWillMount() {
var query = queryString.parse(this.props.location.search);
if (query.token) {
window.localStorage.setItem("jwt", query.token);
store.dispatch(push("/"));
}
}
Here, I am redirecting back to my client from Node.js server after successful Google-Passport authentication, which is redirecting back with token as query param.
I am parsing it with query-string module, saving it and updating the query params in the url with push from react-router-redux.
I have the same problem. After studying and googling, I have resolved my problem:
Right click on the project folder, go to Java EE Tools
, select Generate Deployment Descriptor Stub
. This will create web.xml
in the folder src/main/webapp/WEB-INF
.
Regex with replaceAll.
public class Main
{
public static void main(final String[] argv)
{
String str;
str = "hello\r\njava\r\nbook";
str = str.replaceAll("(\\r|\\n)", "");
System.out.println(str);
}
}
If you only want to remove \r\n when they are pairs (the above code removes either \r or \n) do this instead:
str = str.replaceAll("\\r\\n", "");
put a simple .cmd file in my subfolder with my .ps1 file with the same name, so, for example, a script named "foobar" would have "foobar.ps1" and "foobar.cmd". So to run the .ps1, all I have to do is click the .cmd file from explorer or run the .cmd from a command prompt. I use the same base name because the .cmd file will automatically look for the .ps1 using its own name.
::====================================================================
:: Powershell script launcher
::=====================================================================
:MAIN
@echo off
for /f "tokens=*" %%p in ("%~p0") do set SCRIPT_PATH=%%p
pushd "%SCRIPT_PATH%"
powershell.exe -sta -c "& {.\%~n0.ps1 %*}"
popd
set SCRIPT_PATH=
pause
The pushd/popd allows you to launch the .cmd file from a command prompt without having to change to the specific directory where the scripts are located. It will change to the script directory then when complete go back to the original directory.
You can also take the pause off if you want the command window to disappear when the script finishes.
If my .ps1 script has parameters, I prompt for them with GUI prompts using .NET Forms, but also make the scripts flexible enough to accept parameters if I want to pass them instead. This way I can just double-click it from Explorer and not have to know the details of the parameters since it will ask me for what I need, with list boxes or other forms.
import inspect
file_name = __FILE__
current_line_no = inspect.stack()[0][2]
current_function_name = inspect.stack()[0][3]
#Try printing inspect.stack() you can see current stack and pick whatever you want
It´s possible via Github Organizations. You have to create a new account.
@Alan's answer will do what you're looking for, but this solution fails when you use the responsive capabilities of Bootstrap. In your case, you're using the xs
sizes so you won't notice, but if you used anything else (e.g. col-sm
, col-md
, etc), you'd understand.
Another approach is to play with margins and padding. See the updated fiddle: http://jsfiddle.net/jz8j247x/1/
.left-side {
background-color: blue;
padding-bottom: 1000px;
margin-bottom: -1000px;
height: 100%;
}
.something {
height: 100%;
background-color: red;
padding-bottom: 1000px;
margin-bottom: -1000px;
height: 100%;
}
.row {
background-color: green;
overflow: hidden;
}
The best video playback/encoding library I have ever seen is ffmpeg. It plays everything you throw at it. (It is used by MPlayer.) It is written in C but I found some Java wrappers.
This answer is for those who are using Bootstrap 4.1+ and for those who care about IE 11 as well
Card-deck does not adapt the number visible of cards according to the viewport size.
Above methods work but do not support IE. With the below method, you can achieve similar functionality and responsive cards.
You can manage the number of cards to show/hide in different breakpoints.
In Bootstrap 4.1+ columns are same height by default, just make sure your card/content uses all available space. Run the snippet, you'll understand
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col-sm-6 col-lg-4 mb-3">_x000D_
<div class="card mb-3 h-100">_x000D_
_x000D_
<div class="card-body">_x000D_
<h5 class="card-title">Card title</h5>_x000D_
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
<p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-sm-6 col-lg-4 mb-3">_x000D_
<div class="card mb-3 h-100">_x000D_
<div class="card-body">_x000D_
<h5 class="card-title">Card title</h5>_x000D_
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
<p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-sm-6 col-lg-4 mb-3">_x000D_
<div class="card mb-3 h-100">_x000D_
<div class="card-body">_x000D_
<h5 class="card-title">Card title</h5>_x000D_
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
<p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
I had a similar issue when trying to access a service (old ASMX service). The call would work when accessing via an IP however when calling with an alias I would get the remote name could not be resolved.
Added the following to the config and it resolved the issue:
<system.net>
<defaultProxy enabled="true">
</defaultProxy>
</system.net>
This is actually on the main page of nltk.org:
>>> import nltk
>>> sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
>>> tokens = nltk.word_tokenize(sentence)
>>> tokens
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning',
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']
jd-gui is the best decompiler at the moment. it can handle newer features in Java, as compared to the getting-dusty JAD.
I know I'm a bit late, incase the above answers didn't work, I recommend checking the logs in elasticsearch terminal. I found out that the error message says that i need to update my version from 5.0.0-rc1
to 6.8.0
, i resolved it by updating my maven dependencies to:
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.8.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>6.8.0</version>
</dependency>
This changes my code as well, since InetSocketTransportAddress
is deprecated. I have to change it to TransportAddress
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new TransportAddress(InetAddress.getByName(host), port));
And you also need to add this to your config/elasticsearch.yml file (use your host address)
transport.host: localhost
You need to declare disconnectFunc as a function pointer, not a void pointer. You also need to call it as a function (with parentheses), and no "*" is needed.
This question specifically mentions a single column, so the currently accepted answer works. However, it doesn't generalize to multiple columns. For those interested in a general solution, use the following:
df.replace({False: 0, True: 1}, inplace=True)
This works for a DataFrame that contains columns of many different types, regardless of how many are boolean.
You can also use this:
.dropdown {
height: 0px;
width: 0px;
opacity: .0;
color: white;
}
.dropdown:hover {
height: 20px;
width: 50px;
opacity: 1;
transition: opacity 200ms;
/* Safari */
-webkit-transition: opacity 200ms;
}
You can use std::set
instead of std::map
.
You can store both key and value in std::pair
and the type of container will look like this:
std::set< std::pair<int, std::string> > items;
std::set
will sort it's values both by original keys and values that were stored in std::map
.
You may use fs.unlink(path, callback) function. Here is an example of the function wrapper with "error-back" pattern:
// Dependencies._x000D_
const fs = require('fs');_x000D_
_x000D_
// Delete a file._x000D_
const deleteFile = (filePath, callback) => {_x000D_
// Unlink the file._x000D_
fs.unlink(filePath, (error) => {_x000D_
if (!error) {_x000D_
callback(false);_x000D_
} else {_x000D_
callback('Error deleting the file');_x000D_
}_x000D_
})_x000D_
};
_x000D_
Yes and no. All the common web browsers has a security measure to prevent that. The goal is to prevent people from creating replicas of websites, change the URL to make it look correct, and then be able to trick people and get their info.
However, some HTML5 compatible web browsers has implemented an History API that can be used for something similar to what you want:
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?myNewUrlQuery=1';
window.history.pushState({path:newurl},'',newurl);
}
I tested, and it worked fine. It does not reload the page, but it only allows you to change the URL query. You would not be able to change the protocol or the host values.
For more information:
http://diveintohtml5.info/history.html
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
I have shamelessly pulled some pretty big datasets in memory, and altough it did get sluggish it took maybe 15 Mo of data upwards with pretty intense calculations on the dataset. I doubt you will run into problems with memory unless you have intense calculations on the data and many many rows. Profiling and benchmarking with different mock resultsets will be your best bet to evaluate performance.
There are TWO approaches that you can take to use licensed web-fonts on your pages:
JS font loaders like the one used by Google and Typekit (i.e. WebFont loader) provide CSS classes and callbacks to help manage the FOUT that may occur, or response timeouts when downloading the font.
<head>
<!-- get the required files from 3rd party sources -->
<link href='http://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
<!-- use the font -->
<style>
body {
font-family: 'Roboto', sans-serif;
font-size: 48px;
}
</style>
</head>
@font-face
CSS property is used to enable the font(s).This approach can provides better load performance since you have a more granular control over the characters to include and hence the file-size.
/* get the required local files */
@font-face {
font-family: 'Roboto';
src: url('roboto.eot'); /* IE9 Compat Modes */
src: url('roboto.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('roboto.woff') format('woff'), /* Modern Browsers */
url('roboto.ttf') format('truetype'), /* Safari, Android, iOS */
url('roboto.svg#svgFontName') format('svg'); /* Legacy iOS */
}
/* use the font */
body {
font-family: 'Roboto', sans-serif;
font-size: 48px;
}
Using font hosting services along with @font-face declaration gives best output with respect to overall performance, compatibility and availability.
Source: https://www.artzstudio.com/2012/02/web-font-performance-weighing-fontface-options-and-alternatives/
UPDATE
You can now manually generate the Roboto fonts using instructions that can be found here.
That worked for me:
input:
[complex(a,b) for a,b in zip([1,2,3],[1,2,3])]
output:
[(1+4j), (2+5j), (3+6j)]
This is a variable jQuery uses internally, but had no reason to hide, so it's there to use. Just a heads up, it becomes jquery.ajax.active
next release. There's no documentation because it's exposed but not in the official API, lots of things are like this actually, like jQuery.cache
(where all of jQuery.data()
goes).
I'm guessing here by actual usage in the library, it seems to be there exclusively to support $.ajaxStart()
and $.ajaxStop()
(which I'll explain further), but they only care if it's 0 or not when a request starts or stops. But, since there's no reason to hide it, it's exposed to you can see the actual number of simultaneous AJAX requests currently going on.
When jQuery starts an AJAX request, this happens:
if ( s.global && ! jQuery.active++ ) {
jQuery.event.trigger( "ajaxStart" );
}
This is what causes the $.ajaxStart()
event to fire, the number of connections just went from 0 to 1 (jQuery.active++
isn't 0 after this one, and !0 == true
), this means the first of the current simultaneous requests started. The same thing happens at the other end. When an AJAX request stops (because of a beforeSend
abort via return false
or an ajax call complete
function runs):
if ( s.global && ! --jQuery.active ) {
jQuery.event.trigger( "ajaxStop" );
}
This is what causes the $.ajaxStop()
event to fire, the number of requests went down to 0, meaning the last simultaneous AJAX call finished. The other global AJAX handlers fire in there along the way as well.
first find your binaries file where it is saved. get the path in terminal mine is
C:\Users\LENOVO\Documents\postgresql-9.5.21-1-windows-x64-binaries (1)\pgsql\bin
then find your local user data path, it is in mostly
C:\usr\local\pgsql\data
now all we have to hit following command in the binary terminal path:
C:\Users\LENOVO\Documents\postgresql-9.5.21-1-windows-x64-binaries (1)\pgsql\bin>pg_ctl -D "C:\usr\local\pgsql\data" start
all done!
autovaccum launcher started! cheers!
Try using WGET
:
WGET 'http://localhost/index.php?a=1&b=2&c=3'
One possible solution is to use Ticks:
public long Ticks { get; }
Then in the controller's method:
public DateTime(long ticks);
For controllers that are in the storyboard.
jhilgert00 is this what you were looking for?
-(IBAction)nav_goHome:(id)sender {
UIViewController *myController = [self.storyboard instantiateViewControllerWithIdentifier:@"HomeController"];
[self.navigationController pushViewController: myController animated:YES];
}
OR...
[self performSegueWithIdentifier:@"loginMainSegue" sender:self];
Here is a method to trim a String that has a "," or white space
private String shorterName(String s){
String[] sArr = s.split("\\,|\\s+");
String output = sArr[0];
return output;
}
I think the pro LINQ argument seems to be coming from people who don't have a history with database development (in general).
Especially if using a product like VS DB Pro or Team Suite, many of the arguments made here do not apply, for instance:
Harder to maintain and Test: VS provides full syntax checking, style checking, referential and constraint checking and more. It also provide full unit testing capabilities and refactoring tools.
LINQ makes true unit testing impossible as (in my mind) it fails the ACID test.
Debugging is easier in LINQ: Why? VS allows full step-in from managed code and regular debugging of SPs.
Compiled into a single DLL rather than deployment scripts: Once again, VS comes to the rescue where it can build and deploy full databases or make data-safe incremental changes.
Don't have to learn TSQL with LINQ: No you don't, but you have to learn LINQ - where's the benefit?
I really don't see this as being a benefit. Being able to change something in isolation might sound good in theory, but just because the changes fulfil a contract doesn't mean it's returning the correct results. To be able to determine what the correct results are you need context and you get that context from the calling code.
Um, loosely coupled apps are the ultimate goal of all good programmers as they really do increase flexibility. Being able to change things in isolation is fantastic, and it is your unit tests that will ensure it is still returning appropriate results.
Before you all get upset, I think LINQ has its place and has a grand future. But for complex, data-intensive applications I do not think it is ready to take the place of stored procedures. This was a view I had echoed by an MVP at TechEd this year (they will remain nameless).
EDIT: The LINQ to SQL Stored Procedure side of things is something I still need to read more on - depending on what I find I may alter my above diatribe ;)
This answer follows T-SQL format. I conceptualize this problem as one of a linear-time distance between two date points in datetime format, call them Time1 and Time2; Time1 should be aligned to the 'older in time' value you are dealing with (say a Birth date or a widget Creation date or a journey Start date) and Time2 should be aligned with the 'newer in time' value (say a snapshot date or a widget completion date or a journey checkpoint-reached date).
DECLARE @Time1 DATETIME
SET @Time1 = '12/14/2015'
DECLARE @Time2 DATETIME
SET @Time2 = '12/15/2016'
The solution leverages simple measurement, conversion and calculations of the serial intersections of multiple cycles of different lengths; here: Century,Decade,Year,Month,Day (Thanks Mayan Calendar for the concept!). A quick note of thanks: I thank other contributors to Stack Overflow for showing me some of the component functions in this process that I've stitched together. I've positively rated these in my time on this forum.
First, construct a horizon that is the linear set of the intersections of the Century,Decade,Year,Month cycles, incremental by month. Use the cross join Cartesian function for this. (Think of this as creating the cloth from which we will cut a length between two 'yyyy-mm' points in order to measure distance):
SELECT
Linear_YearMonths = (centuries.century + decades.decade + years.[year] + months.[Month]),
1 AS value
INTO #linear_months
FROM
(SELECT '18' [century] UNION ALL
SELECT '19' UNION ALL
SELECT '20') centuries
CROSS JOIN
(SELECT '0' [decade] UNION ALL
SELECT '1' UNION ALL
SELECT '2' UNION ALL
SELECT '3' UNION ALL
SELECT '4' UNION ALL
SELECT '5' UNION ALL
SELECT '6' UNION ALL
SELECT '7' UNION ALL
SELECT '8' UNION ALL
SELECT '9') decades
CROSS JOIN
(SELECT '1' [year] UNION ALL
SELECT '2' UNION ALL
SELECT '3' UNION ALL
SELECT '4' UNION ALL
SELECT '5' UNION ALL
SELECT '6' UNION ALL
SELECT '7' UNION ALL
SELECT '8' UNION ALL
SELECT '9' UNION ALL
SELECT '0') years
CROSS JOIN
(SELECT '-01' [month] UNION ALL
SELECT '-02' UNION ALL
SELECT '-03' UNION ALL
SELECT '-04' UNION ALL
SELECT '-05' UNION ALL
SELECT '-06' UNION ALL
SELECT '-07' UNION ALL
SELECT '-08' UNION ALL
SELECT '-09' UNION ALL
SELECT '-10' UNION ALL
SELECT '-11' UNION ALL
SELECT '-12') [months]
ORDER BY 1
Then, convert your Time1 and Time2 date points into the 'yyyy-mm' format (Think of these as the coordinate cut points on the whole cloth). Retain the original datetime versions of the points as well:
SELECT
Time1 = @Time1,
[YYYY-MM of Time1] = CASE
WHEN LEFT(MONTH(@Time1),1) <> '1' OR MONTH(@Time1) = '1'
THEN (CAST(YEAR(@Time1) AS VARCHAR) + '-' + '0' + CAST(MONTH(@Time1) AS VARCHAR))
ELSE (CAST(YEAR(@Time1) AS VARCHAR) + '-' + CAST(MONTH(@Time1) AS VARCHAR))
END,
Time2 = @Time2,
[YYYY-MM of Time2] = CASE
WHEN LEFT(MONTH(@Time2),1) <> '1' OR MONTH(@Time2) = '1'
THEN (CAST(YEAR(@Time2) AS VARCHAR) + '-' + '0' + CAST(MONTH(@Time2) AS VARCHAR))
ELSE (CAST(YEAR(@Time2) AS VARCHAR) + '-' + CAST(MONTH(@Time2) AS VARCHAR))
END
INTO #datepoints
Then, Select the ordinal distance of 'yyyy-mm' units, less one to convert to cardinal distance (i.e. cut a piece of cloth from the whole cloth at the identified cut points and get its raw measurement):
SELECT
d.*,
Months_Between = (SELECT (SUM(l.value) - 1) FROM #linear_months l
WHERE l.[Linear_YearMonths] BETWEEN d.[YYYY-MM of Time1] AND d.[YYYY-MM of Time2])
FROM #datepoints d
Raw Output: I call this a 'raw distance' because the month component of the 'yyyy-mm' cardinal distance may be one too many; the day cycle components within the month need to be compared to see if this last month value should count. In this example specifically, the raw output distance is '12'. But this wrong as 12/14 is before 12/15, so therefore only 11 full months have lapsed--its just one day shy of lapsing through the 12th month. We therefore have to bring in the intra-month day cycle to get to a final answer. Insert a 'month,day' position comparison between the to determine if the latest date point month counts nominally, or not:
SELECT
d.*,
Months_Between = (SELECT (SUM(l.value) - 1) FROM AZ_VBP.[MY].[edg_Linear_YearMonths] l
WHERE l.[Linear_YearMonths] BETWEEN d.[YYYY-MM of Time1] AND d.[YYYY-MM of Time2])
+ (CASE WHEN DAY(Time1) < DAY(Time2)
THEN -1
ELSE 0
END)
FROM #datepoints d
Final Output: The correct answer of '11' is now our output. And so, I hope this helps. Thanks!
I learned all my Regex from this website: http://www.zytrax.com/tech/web/regex.htm. Google on 'Regex tutorials' and you'll find loads of helful articles.
String regex = "[a-zA-Z]*\.jpg";
System.out.println ("somthing.jpg".matches (regex));
returns true.
There are all sorts of ways to get the Last Inserted ID but the easiest way I have found is by simply retrieving it from the TableAdapter in the DataSet like so:
<Your DataTable Class> tblData = new <Your DataTable Class>();
<Your Table Adapter Class> tblAdpt = new <Your Table Adapter Class>();
/*** Initialize and update Table Data Here ***/
/*** Make sure to call the EndEdit() method ***/
/*** of any Binding Sources before update ***/
<YourBindingSource>.EndEdit();
//Update the Dataset
tblAdpt.Update(tblData);
//Get the New ID from the Table Adapter
long newID = tblAdpt.Adapter.InsertCommand.LastInsertedId;
Hope this Helps ...
A new (Keller) method is supposed to improve speed over the -9999px method:
.hide-text {
text-indent: 100%;
white-space: nowrap;
overflow: hidden;
}
recommended here:http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement/
Adaptation of @AndiDog version for big file:
static const int K_READ_BUF_SIZE{ 1024 * 16 };
std::optional<std::string> CalcSha256(std::string filename)
{
// Initialize openssl
SHA256_CTX context;
if(!SHA256_Init(&context))
{
return std::nullopt;
}
// Read file and update calculated SHA
char buf[K_READ_BUF_SIZE];
std::ifstream file(filename, std::ifstream::binary);
while (file.good())
{
file.read(buf, sizeof(buf));
if(!SHA256_Update(&context, buf, file.gcount()))
{
return std::nullopt;
}
}
// Get Final SHA
unsigned char result[SHA256_DIGEST_LENGTH];
if(!SHA256_Final(result, &context))
{
return std::nullopt;
}
// Transform byte-array to string
std::stringstream shastr;
shastr << std::hex << std::setfill('0');
for (const auto &byte: result)
{
shastr << std::setw(2) << (int)byte;
}
return shastr.str();
}
You can try the below:
function formatAMPM() {
var date = new Date();
var currDate = date.getDate();
var hours = date.getHours();
var dayName = getDayName(date.getDay());
var minutes = date.getMinutes();
var monthName = getMonthName(date.getMonth());
var year = date.getFullYear();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = dayName + ' ' + monthName + ' ' + currDate + ' ' + year + ' ' + hours + ':' + minutes + ' ' + ampm;
alert(strTime);
}
function getMonthName(month) {
var ar = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
return ar[month];
}
function getDayName(day) {
var ar1 = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
return ar1[day];
}
EDIT: Refer here for a working demo.
Try using the ASCII code for those values:
^([a-zA-Z0-9 .\x26\x27-]+)$
\x26
= &
\x27
= '
The format is \xnn
where nn is the two-digit hexadecimal character code. You could also use \unnnn
to specify a four-digit hex character code for the Unicode character.
When you trying to build and run the current scheme but encounter this alert message:
"The run destination iPhone is not valid for Running the scheme."
Plus you already check your phone and it is connect to your Mac properly, all you need to do is just simply restart your Xcode and build it again. That will do the job.
you can use those function it's so easy the First one for encryption so you just call the function and send the text you wanna encrypt it and take the result from encryptWithAES function and send it to decrypt Function like this:
const CryptoJS = require("crypto-js");
//The Function Below To Encrypt Text
const encryptWithAES = (text) => {
const passphrase = "My Secret Passphrase";
return CryptoJS.AES.encrypt(text, passphrase).toString();
};
//The Function Below To Decrypt Text
const decryptWithAES = (ciphertext) => {
const passphrase = "My Secret Passphrase";
const bytes = CryptoJS.AES.decrypt(ciphertext, passphrase);
const originalText = bytes.toString(CryptoJS.enc.Utf8);
return originalText;
};
let encryptText = encryptWithAES("YAZAN");
//EncryptedText==> //U2FsdGVkX19GgWeS66m0xxRUVxfpI60uVkWRedyU15I=
let decryptText = decryptWithAES(encryptText);
//decryptText==> //YAZAN
Working fiddle:
$.ajax({
url: 'https://api.flightstats.com/flex/schedules/rest/v1/jsonp/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59',
dataType: 'JSONP',
jsonpCallback: 'callback',
type: 'GET',
success: function (data) {
console.log(data);
}
});
I had to manually set the callback to callback
, since that's all the remote service seems to support. I also changed the url to specify that I wanted jsonp.
subprocess.run
is the recommended approach as of Python 3.5 if your code does not need to maintain compatibility with earlier Python versions. It's more consistent and offers similar ease-of-use as Envoy. (Piping isn't as straightforward though. See this question for how.)
Here's some examples from the documentation.
Run a process:
>>> subprocess.run(["ls", "-l"]) # Doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)
Raise on failed run:
>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
Capture output:
>>> subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n')
I recommend trying Envoy. It's a wrapper for subprocess, which in turn aims to replace the older modules and functions. Envoy is subprocess for humans.
Example usage from the README:
>>> r = envoy.run('git config', data='data to pipe in', timeout=2)
>>> r.status_code
129
>>> r.std_out
'usage: git config [options]'
>>> r.std_err
''
Pipe stuff around too:
>>> r = envoy.run('uptime | pbcopy')
>>> r.command
'pbcopy'
>>> r.status_code
0
>>> r.history
[<Response 'uptime'>]
Server.MapPath specifies the relative or virtual path to map to a physical directory.
Server.MapPath(".")
1 returns the current physical directory of the file (e.g. aspx) being executedServer.MapPath("..")
returns the parent directoryServer.MapPath("~")
returns the physical path to the root of the applicationServer.MapPath("/")
returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)An example:
Let's say you pointed a web site application (http://www.example.com/
) to
C:\Inetpub\wwwroot
and installed your shop application (sub web as virtual directory in IIS, marked as application) in
D:\WebApps\shop
For example, if you call Server.MapPath()
in following request:
http://www.example.com/shop/products/GetProduct.aspx?id=2342
then:
Server.MapPath(".")
1 returns D:\WebApps\shop\products
Server.MapPath("..")
returns D:\WebApps\shop
Server.MapPath("~")
returns D:\WebApps\shop
Server.MapPath("/")
returns C:\Inetpub\wwwroot
Server.MapPath("/shop")
returns D:\WebApps\shop
If Path starts with either a forward slash (/
) or backward slash (\
), the MapPath()
returns a path as if Path was a full, virtual path.
If Path doesn't start with a slash, the MapPath()
returns a path relative to the directory of the request being processed.
Note: in C#, @
is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.
Footnotes
Server.MapPath(null)
and Server.MapPath("")
will produce this effect too.Its simple. Just use css.
<style>
@page { size: auto; margin: 0mm; }
</style>
You could achieve this quite easily with jQuery by registering for the click event of the anchors (with class="movie") and using the .load()
method to send an AJAX request and replace the contents of the summary div:
$(function() {
$('.movie').click(function() {
$('#summary').load(this.href);
// it's important to return false from the click
// handler in order to cancel the default action
// of the link which is to redirect to the url and
// execute the AJAX request
return false;
});
});
Answer:
public void Print(string FileName)
{
StringBuilder logMessage = new StringBuilder();
logMessage.AppendLine(string.Format(CultureInfo.InvariantCulture, "-------------------[ START - {0} - {1} -------------------]", MethodBase.GetCurrentMethod(), DateTime.Now.ToShortDateString()));
logMessage.AppendLine(string.Format(CultureInfo.InvariantCulture, "Parameter: 1: [Name - {0}, Value - {1}", "None]", Convert.ToString("")));
try
{
if (string.IsNullOrWhiteSpace(FileName)) return; // Prevents execution of below statements if filename is not selected.
PrintDocument pd = new PrintDocument();
//Disable the printing document pop-up dialog shown during printing.
PrintController printController = new StandardPrintController();
pd.PrintController = printController;
//For testing only: Hardcoded set paper size to particular paper.
//pd.PrinterSettings.DefaultPageSettings.PaperSize = new PaperSize("Custom 6x4", 720, 478);
//pd.DefaultPageSettings.PaperSize = new PaperSize("Custom 6x4", 720, 478);
pd.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
pd.PrinterSettings.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
pd.PrintPage += (sndr, args) =>
{
System.Drawing.Image i = System.Drawing.Image.FromFile(FileName);
//Adjust the size of the image to the page to print the full image without loosing any part of the image.
System.Drawing.Rectangle m = args.MarginBounds;
//Logic below maintains Aspect Ratio.
if ((double)i.Width / (double)i.Height > (double)m.Width / (double)m.Height) // image is wider
{
m.Height = (int)((double)i.Height / (double)i.Width * (double)m.Width);
}
else
{
m.Width = (int)((double)i.Width / (double)i.Height * (double)m.Height);
}
//Calculating optimal orientation.
pd.DefaultPageSettings.Landscape = m.Width > m.Height;
//Putting image in center of page.
m.Y = (int)((((System.Drawing.Printing.PrintDocument)(sndr)).DefaultPageSettings.PaperSize.Height - m.Height) / 2);
m.X = (int)((((System.Drawing.Printing.PrintDocument)(sndr)).DefaultPageSettings.PaperSize.Width - m.Width) / 2);
args.Graphics.DrawImage(i, m);
};
pd.Print();
}
catch (Exception ex)
{
log.ErrorFormat("Error : {0}\n By : {1}-{2}", ex.ToString(), this.GetType(), MethodBase.GetCurrentMethod().Name);
}
finally
{
logMessage.AppendLine(string.Format(CultureInfo.InvariantCulture, "-------------------[ END - {0} - {1} -------------------]", MethodBase.GetCurrentMethod().Name, DateTime.Now.ToShortDateString()));
log.Info(logMessage.ToString());
}
}
(Update: overlooked a fault in the matter, I have corrected)
(Update2: I wrote from memory the code screwed up, repaired it)
(Update3: check on SQLFiddle)
create table Derived_Values
(
BusinessUnit nvarchar(100) not null
,Questions nvarchar(100) not null
,Answer nvarchar(100)
)
go
ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);
create table Derived_Values_Test
(
BusinessUnit nvarchar(150)
,Questions nvarchar(100)
,Answer nvarchar(100)
)
go
CREATE TRIGGER trgAfterUpdate ON [Derived_Values]
FOR UPDATE
AS
begin
declare @BusinessUnit nvarchar(50)
set @BusinessUnit = 'Updated Record -- After Update Trigger.'
insert into
[Derived_Values_Test]
--(BusinessUnit,Questions, Answer)
SELECT
@BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
FROM
inserted i
inner join deleted d on i.BusinessUnit = d.BusinessUnit
end
go
CREATE TRIGGER trgAfterDelete ON [Derived_Values]
FOR UPDATE
AS
begin
declare @BusinessUnit nvarchar(50)
set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'
insert into
[Derived_Values_Test]
--(BusinessUnit,Questions, Answer)
SELECT
@BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
FROM
deleted d
end
go
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')
UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');
delete Derived_Values;
and then:
SELECT * FROM Derived_Values;
go
select * from Derived_Values_Test;
Record Count: 0;
BUSINESSUNIT QUESTIONS ANSWER
Updated Record -- After Update Trigger.BU1 Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1 Q11 A11
Updated Record -- After Update Trigger.BU1 Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1 Q12 A12
Updated Record -- After Update Trigger.BU2 Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2 Q21 A21
Updated Record -- After Update Trigger.BU2 Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2 Q22 A22
(Update4: If you want to sync: SQLFiddle)
create table Derived_Values
(
BusinessUnit nvarchar(100) not null
,Questions nvarchar(100) not null
,Answer nvarchar(100)
)
go
ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);
create table Derived_Values_Test
(
BusinessUnit nvarchar(150) not null
,Questions nvarchar(100) not null
,Answer nvarchar(100)
)
go
ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);
CREATE TRIGGER trgAfterInsert ON [Derived_Values]
FOR INSERT
AS
begin
insert
[Derived_Values_Test]
(BusinessUnit,Questions,Answer)
SELECT
i.BusinessUnit, i.Questions, i.Answer
FROM
inserted i
end
go
CREATE TRIGGER trgAfterUpdate ON [Derived_Values]
FOR UPDATE
AS
begin
declare @BusinessUnit nvarchar(50)
set @BusinessUnit = 'Updated Record -- After Update Trigger.'
update
[Derived_Values_Test]
set
--BusinessUnit = i.BusinessUnit
--,Questions = i.Questions
Answer = i.Answer
from
[Derived_Values]
inner join inserted i
on
[Derived_Values].BusinessUnit = i.BusinessUnit
and
[Derived_Values].Questions = i.Questions
end
go
CREATE TRIGGER trgAfterDelete ON [Derived_Values]
FOR DELETE
AS
begin
delete
[Derived_Values_Test]
from
[Derived_Values_Test]
inner join deleted d
on
[Derived_Values_Test].BusinessUnit = d.BusinessUnit
and
[Derived_Values_Test].Questions = d.Questions
end
go
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')
UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');
--delete Derived_Values;
And then:
SELECT * FROM Derived_Values;
go
select * from Derived_Values_Test;
BUSINESSUNIT QUESTIONS ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22
BUSINESSUNIT QUESTIONS ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22
If you are using XAMPP as your server, you'll find a logs directory as a child of the XAMPP directory. If you have not tried XAMPP, which runs on any system (Windows, Mac OS & Linux) find more here: http://www.apachefriends.org/en/xampp.html
Oftentimes there's a need to override existing rules, so appending new styles to the HEAD doesn't work in every case.
I came up with this simple function that summarizes all not valid "append to the BODY" approaches and is just more convenient to use and debug (IE8+).
window.injectCSS = (function(doc){
// wrapper for all injected styles and temp el to create them
var wrap = doc.createElement('div');
var temp = doc.createElement('div');
// rules like "a {color: red}" etc.
return function (cssRules) {
// append wrapper to the body on the first call
if (!wrap.id) {
wrap.id = 'injected-css';
wrap.style.display = 'none';
doc.body.appendChild(wrap);
}
// <br> for IE: http://goo.gl/vLY4x7
temp.innerHTML = '<br><style>'+ cssRules +'</style>';
wrap.appendChild( temp.children[1] );
};
})(document);
As this is the first result on google for "php mysql transaction", I thought I'd add an answer that explicitly demonstrates how to do this with mysqli (as the original author wanted examples). Here's a simplified example of transactions with PHP/mysqli:
// let's pretend that a user wants to create a new "group". we will do so
// while at the same time creating a "membership" for the group which
// consists solely of the user themselves (at first). accordingly, the group
// and membership records should be created together, or not at all.
// this sounds like a job for: TRANSACTIONS! (*cue music*)
$group_name = "The Thursday Thumpers";
$member_name = "EleventyOne";
$conn = new mysqli($db_host,$db_user,$db_passwd,$db_name); // error-check this
// note: this is meant for InnoDB tables. won't work with MyISAM tables.
try {
$conn->autocommit(FALSE); // i.e., start transaction
// assume that the TABLE groups has an auto_increment id field
$query = "INSERT INTO groups (name) ";
$query .= "VALUES ('$group_name')";
$result = $conn->query($query);
if ( !$result ) {
$result->free();
throw new Exception($conn->error);
}
$group_id = $conn->insert_id; // last auto_inc id from *this* connection
$query = "INSERT INTO group_membership (group_id,name) ";
$query .= "VALUES ('$group_id','$member_name')";
$result = $conn->query($query);
if ( !$result ) {
$result->free();
throw new Exception($conn->error);
}
// our SQL queries have been successful. commit them
// and go back to non-transaction mode.
$conn->commit();
$conn->autocommit(TRUE); // i.e., end transaction
}
catch ( Exception $e ) {
// before rolling back the transaction, you'd want
// to make sure that the exception was db-related
$conn->rollback();
$conn->autocommit(TRUE); // i.e., end transaction
}
Also, keep in mind that PHP 5.5 has a new method mysqli::begin_transaction. However, this has not been documented yet by the PHP team, and I'm still stuck in PHP 5.3, so I can't comment on it.
What is a CSS map file?
It is a JSON format file that links the CSS file to its source files, normally, files written in preprocessors (i.e., Less, Sass, Stylus, etc.), this is in order do a live debug to the source files from the web browser.
What is CSS preprocessor? Examples: Sass, Less, Stylus
It is a CSS generator tool that uses programming power to generate CSS robustly and quickly.
Found this absolute hack that actually works quite well:
https://codepen.io/nikitahl/pen/vyZbwR
Not CSS only though.
The basic gist is to have a container on the dropdown, .select-container
in this case. That container has it's ::before
set up to display content
based on its data-content
attribute/dataset, along with all of the overflow:hidden; text-overflow: ellipsis;
and sizing necessary to make the ellipsis work.
When the select changes, javascript assigns the value (or you could retrieve the text of the option out of the select.options
list) to the dataset.content of the container, and voila!
Copying content of the codepen here:
var selectContainer = document.querySelector(".select-container");_x000D_
var select = selectContainer.querySelector(".select");_x000D_
select.value = "lingua latina non penis canina";_x000D_
_x000D_
selectContainer.dataset.content = select.value;_x000D_
_x000D_
function handleChange(e) {_x000D_
selectContainer.dataset.content = e.currentTarget.value;_x000D_
console.log(select.value);_x000D_
}_x000D_
_x000D_
select.addEventListener("change", handleChange);
_x000D_
span {_x000D_
margin: 0 10px 0 0;_x000D_
}_x000D_
_x000D_
.select-container {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
}_x000D_
_x000D_
.select-container::before {_x000D_
content: attr(data-content);_x000D_
position: absolute;_x000D_
top: 0;_x000D_
right: 10px;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
padding: 7px;_x000D_
font: 11px Arial, sans-serif;_x000D_
white-space: nowrap;_x000D_
text-overflow: ellipsis;_x000D_
overflow: hidden;_x000D_
text-transform: capitalize;_x000D_
pointer-events: none;_x000D_
}_x000D_
_x000D_
.select {_x000D_
width: 80px;_x000D_
padding: 5px;_x000D_
appearance: none;_x000D_
background: transparent url("https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-arrow-down-b-128.png") no-repeat calc(~"100% - 5px") 7px;_x000D_
background-size: 10px 10px;_x000D_
color: transparent;_x000D_
}_x000D_
_x000D_
.regular {_x000D_
display: inline-block;_x000D_
margin: 10px 0 0;_x000D_
.select {_x000D_
color: #000;_x000D_
}_x000D_
}
_x000D_
<span>Hack:</span><div class="select-container" data-content="">_x000D_
<select class="select" id="words">_x000D_
<option value="lingua latina non penis canina">Lingua latina non penis canina</option>_x000D_
<option value="lorem">Lorem</option>_x000D_
<option value="ipsum">Ipsum</option>_x000D_
<option value="dolor">Dolor</option>_x000D_
<option value="sit">Sit</option>_x000D_
<option value="amet">Amet</option>_x000D_
<option value="lingua">Lingua</option>_x000D_
<option value="latina">Latina</option>_x000D_
<option value="non">Non</option>_x000D_
<option value="penis">Penis</option>_x000D_
<option value="canina">Canina</option>_x000D_
</select>_x000D_
</div>_x000D_
<br />_x000D_
_x000D_
<span>Regular:</span>_x000D_
<div class="regular">_x000D_
<select style="width: 80px;">_x000D_
<option value="lingua latina non penis canina">Lingua latina non penis canina</option>_x000D_
<option value="lorem">Lorem</option>_x000D_
<option value="ipsum">Ipsum</option>_x000D_
<option value="dolor">Dolor</option>_x000D_
<option value="sit">Sit</option>_x000D_
<option value="amet">Amet</option>_x000D_
<option value="lingua">Lingua</option>_x000D_
<option value="latina">Latina</option>_x000D_
<option value="non">Non</option>_x000D_
<option value="penis">Penis</option>_x000D_
<option value="canina">Canina</option>_x000D_
</select>_x000D_
</div>
_x000D_
Try this:
if (value instanceof Array) {
alert('value is Array!');
} else {
alert('Not an array');
}
Sorry, this is not possible with MS SQL Server (possible though with PostgreSQL):
select lastname + ', ' + firstname as fullname
from person
group by fullname
Otherwise just use this:
select x.fullname
from
(
select lastname + ', ' + firstname as fullname
from person
) as x
group by x.fullname
Or this:
select lastname + ', ' + firstname as fullname
from person
group by lastname, firstname -- no need to put the ', '
The above query is faster, groups the fields first, then compute those fields.
The following query is slower (it tries to compute first the select expression, then it groups the records based on that computation).
select lastname + ', ' + firstname as fullname
from person
group by lastname + ', ' + firstname
This works for me
var dataTable = $('#HelpdeskOverview').dataTable();
var oSettings = dataTable.fnSettings();
dataTable.fnClearTable(this);
for (var i=0; i<json.aaData.length; i++)
{
dataTable.oApi._fnAddData(oSettings, json.aaData[i]);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
dataTable.fnDraw();
About using Tuple in Converter, it would be better to use 'object' instead of 'string', so that it works for all types of objects without limitation of 'string' object.
public class YourConverter : IMultiValueConverter
{
public object Convert(object[] values, ...)
{
Tuple<object, object> tuple = new Tuple<object, object>(values[0], values[1]);
return tuple;
}
}
Then execution logic in Command could be like this
public void OnExecute(object parameter)
{
var param = (Tuple<object, object>) parameter;
// e.g. for two TextBox object
var txtZip = (System.Windows.Controls.TextBox)param.Item1;
var txtCity = (System.Windows.Controls.TextBox)param.Item2;
}
and multi-bind with converter to create the parameters (with two TextBox objects)
<Button Content="Zip/City paste" Command="{Binding PasteClick}" >
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource YourConvert}">
<Binding ElementName="txtZip"/>
<Binding ElementName="txtCity"/>
</MultiBinding>
</Button.CommandParameter>
</Button>
Ruby version:
caps = Selenium::WebDriver::Remote::Capabilities.chrome("chromeOptions" => {"args"=> ["--window-size=1280,960"]})
url = "http://localhost:9515" # if you are using local chrome or url = Browserstack/ saucelabs hub url if you are using cloud service providers.
Selenium::WebDriver.for(:remote, :url => url, :desired_capabilities => caps)
resize chrome is buggy in latest chromedrivers , it fails intermittanly with this failure message.
unknown error: cannot get automation extension
from timeout: cannot determine loading status
from timeout: Timed out receiving message from renderer: -65.294
(Session info: chrome=56.0.2924.76)
(Driver info: chromedriver=2.28.455517 (2c6d2707d8ea850c862f04ac066724273981e88f)
And resizeTo via javascript also not supported for chrome started via selenium webdriver. So the last option was using command line switches.
I had problems getting nested directories to be ignored; the top directory I wanted to ignore wouldn't show with 'svn status' but all the subdirs did. This is probably self-evident to everyone else, but I thought I'd share it:
EXAMPLE:
/trunk
/trunk/cache
/trunk/cache/subdir1
/trunk/cache/subdir2
cd /trunk
svn ps svn:ignore . /cache
cd /trunk/cache
svn ps svn:ignore . *
svn ci
It looks like this is the case when Chrome is not compliant with WebSocket standard. When the server initiates close and sends close frame to a client, Chrome considers this to be an error and reports it to JS side with code 1006 and no reason message. In my tests, Chrome never responds to server-initiated close frames (close code 1000) suggesting that code 1006 probably means that Chrome is reporting its own internal error.
P.S. Firefox v57.00 handles this case properly and successfully delivers server's reason message to JS side.
This solution is for those users who do not want to set PATH.
Sometimes setting PATH may not be desired. In my case, I had Anaconda installed and another software with a Python installation required for accessing the API, and setting PATH was creating conflicts which were difficult to resolve.
Under the Anaconda
directory (in this case Anaconda3) there is a subdirectory called envs
where all the environments are stored. When using conda activate some-environment
replace some-environment
with the actual directory location of the environment.
In my case the command is as follows.
conda activate C:\ProgramData\Anaconda3\envs\some-environment
You could store those objects on a database. If you don't want the overhead of a full blown database server you can use an embedded one like HSQLDB. Then you can use Hibernate or BeanKeeper (simpler to use) or other ORM to map objects to tables. You keep using the OO model and get the advanced storage and querying benefits from a database.
Try this (using default keyword)
bool foo = default(bool); if (foo) { }
You can of course use a loop, or you can insert them in a single statement, e.g.
Insert into db
(names,email,password)
Values
('abc','def','mypassword')
,('ghi','jkl','mypassword2')
,('mno','pqr','mypassword3')
It really depends where you're getting your data from.
If you use a loop, wrapping it in a transaction will make it a bit faster.
UPDATE
What if i want to insert unique names?
If you want to insert unique names, then you need to generate data with unique names. One way to do this is to use Visual Studio to generate test data.
you can use dump function and print it like this
{{ dump(MyVar) }}
but there is one nice thing too, if you don't set any argument to dump function, it will print all variables are available, like
{{ dump() }}
why you dont just dump the mysql database but with extension when you run without --single-transaction you will interrupt the connection to other clients:
mysqldump --host=hostname.de --port=0000 --user=username --password=password --single-transaction --skip-add-locks --skip-lock-tables --default-character-set=utf8 datenbankname > mysqlDBBackup.sql
after that read out the file and search for what you want.... in Strings.....
With minimal editing to your code (Not sure if they've taught classes or not in your course), change:
def close_window(root):
root.destroy()
to
def close_window():
window.destroy()
and it should work.
Explanation:
Your version of close_window
is defined to expect a single argument, namely root
. Subsequently, any calls to your version of close_window
need to have that argument, or Python will give you a run-time error.
When you created a Button
, you told the button to run close_window
when it is clicked. However, the source code for Button widget is something like:
# class constructor
def __init__(self, some_args, command, more_args):
#...
self.command = command
#...
# this method is called when the user clicks the button
def clicked(self):
#...
self.command() # Button calls your function with no arguments.
#...
As my code states, the Button
class will call your function with no arguments. However your function is expecting an argument. Thus you had an error. So, if we take out that argument, so that the function call will execute inside the Button class, we're left with:
def close_window():
root.destroy()
That's not right, though, either, because root
is never assigned a value. It would be like typing in print(x)
when you haven't defined x
, yet.
Looking at your code, I figured you wanted to call destroy
on window
, so I changed root
to window
.
Is this what you are trying to do?
# Our data
text <- c("F.US.CLE.V13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13",
"F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13",
"F.US.DL.U13", "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.Z13", "F.US.DL.Z13"
)
# Split into individual elements by the '.' character
# Remember to escape it, because '.' by itself matches any single character
elems <- unlist( strsplit( text , "\\." ) )
# We know the dataframe should have 4 columns, so make a matrix
m <- matrix( elems , ncol = 4 , byrow = TRUE )
# Coerce to data.frame - head() is just to illustrate the top portion
head( as.data.frame( m ) )
# V1 V2 V3 V4
#1 F US CLE V13
#2 F US CA6 U13
#3 F US CA6 U13
#4 F US CA6 U13
#5 F US CA6 U13
#6 F US CA6 U13
It is definitely not the case the question was about, but as it is the first search result while googling the error message, I'll leave it here.
First of all, check if docker service is running using the following command:
systemctl status docker.service
If it is not running, try starting it:
sudo systemctl start docker.service
... and check the status again:
systemctl status docker.service
If it has not started, investigate the reason. Probably, you have modified a config file and made an error (like I did while modifying /etc/docker/daemon.json
)
for a lightweight list that does not copy the entries, you may use sth like this:
List<Object> mergedList = new ConcatList<>(list1, list2);
here the implementation:
public class ConcatList<E> extends AbstractList<E> {
private final List<E> list1;
private final List<E> list2;
public ConcatList(final List<E> list1, final List<E> list2) {
this.list1 = list1;
this.list2 = list2;
}
@Override
public E get(final int index) {
return getList(index).get(getListIndex(index));
}
@Override
public E set(final int index, final E element) {
return getList(index).set(getListIndex(index), element);
}
@Override
public void add(final int index, final E element) {
getList(index).add(getListIndex(index), element);
}
@Override
public E remove(final int index) {
return getList(index).remove(getListIndex(index));
}
@Override
public int size() {
return list1.size() + list2.size();
}
@Override
public void clear() {
list1.clear();
list2.clear();
}
private int getListIndex(final int index) {
final int size1 = list1.size();
return index >= size1 ? index - size1 : index;
}
private List<E> getList(final int index) {
return index >= list1.size() ? list2 : list1;
}
}
Do note that it needs to be in the numeric data type in the first place.
import pandas as pd
df['column'] = pd.to_numeric(df['column'], errors='coerce')
Next find the mean on one column or for all numeric columns using describe()
.
df['column'].mean()
df.describe()
Example of result from describe:
column
count 62.000000
mean 84.678548
std 216.694615
min 13.100000
25% 27.012500
50% 41.220000
75% 70.817500
max 1666.860000
If you don't want to use the url helper, you can get the same results by using the following variable:
$this->config->config['base_url']
It will return the base url for you with no extra steps required.
I used the below solution and it worked for me.
if (window.navigator.msSaveOrOpenBlob) {_x000D_
var blob = new Blob([decodeURIComponent(encodeURI(result.data))], {_x000D_
type: "text/csv;charset=utf-8;"_x000D_
});_x000D_
navigator.msSaveBlob(blob, 'filename.csv');_x000D_
} else {_x000D_
var a = document.createElement('a');_x000D_
a.href = 'data:attachment/csv;charset=utf-8,' + encodeURI(result.data);_x000D_
a.target = '_blank';_x000D_
a.download = 'filename.csv';_x000D_
document.body.appendChild(a);_x000D_
a.click();_x000D_
}
_x000D_
An alternative answer would be this.
<div id="container">
<div id="centered"> </div>
</div>
and the css:
#container {
height: 400px;
width: 400px;
background-color: lightblue;
text-align: center;
}
#container:before {
height: 100%;
content: '';
display: inline-block;
vertical-align: middle;
}
#centered {
width: 100px;
height: 100px;
background-color: blue;
display: inline-block;
vertical-align: middle;
margin: 0 auto;
}
In order to write into a file in Python, we need to open it in write w
, append a
or exclusive creation x
mode.
We need to be careful with the w
mode, as it will overwrite into the file if it already exists. Due to this, all the previous data are erased.
Writing a string or sequence of bytes (for binary files) is done using the write() method. This method returns the number of characters written to the file.
with open('Failed.py','w',encoding = 'utf-8') as f:
f.write("Write what you want to write in\n")
f.write("this file\n\n")
This program will create a new file named Failed.py
in the current directory if it does not exist. If it does exist, it is overwritten.
We must include the newline characters ourselves to distinguish the different lines.
Since we are on IO5 now, you no longer need to write images to disk neccessarily.
You are now able to set "allow external storage" on an coredata binary attribute.
According to apples release notes it means the following:
Small data values like image thumbnails may be efficiently stored in a database, but large photos or other media are best handled directly by the file system. You can now specify that the value of a managed object attribute may be stored as an external record - see setAllowsExternalBinaryDataStorage: When enabled, Core Data heuristically decides on a per-value basis if it should save the data directly in the database or store a URI to a separate file which it manages for you. You cannot query based on the contents of a binary data property if you use this option.
You would still need to go through the DataTable
class. But you can do so using your DataRow
instance by using the Table
property.
foreach (DataColumn c in dr.Table.Columns) //loop through the columns.
{
MessageBox.Show(c.ColumnName);
}
When you normalize a matrix using NORM_L1, you are dividing every pixel value by the sum of absolute values of all the pixels in the image. As a result, all pixel values become much less than 1 and you get a black image. Try NORM_MINMAX instead of NORM_L1.
Ahahaha, here's a funny way I just came up with to do this:
select SYSDATE - ROWNUM
from shipment_weights sw
where ROWNUM < 365;
where shipment_weights is any large table;
Aergistal's answer works, but I found that converting to mp4 can make some m3u8 videos broken. If you are stuck with this problem, try to convert them to mkv, and convert them to mp4 later.