this.form.submit();
This is probably your best bet. Especially if you are not already using jQuery in your project, there is no need to add it (or any other JS library) just for this purpose.
In python 3, you can use:
import locale
locale.setlocale( locale.LC_ALL, 'English_United States.1252' )
locale.currency( 1234.50, grouping = True )
Output
'$1,234.50'
I had the same issue. I had a backup of my C:\xampp\mysql\data
folder. But integrating it with the newly installed xampp
had issues. So I located the C:\xampp\mysql\bin\my.ini
file and directed innodb_data_home_dir = "C:/xampp/mysql/data"
to my backed-up data folder and it worked flawlessly.
Try this it works
document.querySelector('[attribute="value"]')
example :
document.querySelector('[role="button"]')
$.ajax({
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
alert(location.ip);
}
});
This code will work https sites too
C99 added a bool
type whose semantics are fundamentally different from those of just about all integer types that had existed before in C, including user-defined and compiler-extension types intended for such purposes, and which some programs may have "type-def"ed to bool
.
For example, given bool a = 0.1, b=2, c=255, d=256;
, the C99 bool
type would set all four objects to 1. If a C89 program used typedef unsigned char bool
, the objects would receive 0, 1, 255, and 0, respectively. If it used char
, the values might be as above, or c
might be -1. If it had used a compiler-extension bit
or __bit
type, the results would likely be 0, 0, 1, 0 (treating bit
in a way equivalent to an unsigned bit-field of size 1, or an unsigned integer type with one value bit).
Simply put, an endpoint is one end of a communication channel. When an API interacts with another system, the touch-points of this communication are considered endpoints. For APIs, an endpoint can include a URL of a server or service. Each endpoint is the location from which APIs can access the resources they need to carry out their function.
APIs work using ‘requests’ and ‘responses.’ When an API requests information from a web application or web server, it will receive a response. The place that APIs send requests and where the resource lives, is called an endpoint.
Reference: https://smartbear.com/learn/performance-monitoring/api-endpoints/
I've got this error just on devices with API lower that 21. In my case, I have had to work with a project where multiDexEnabled
option in build.gradle
was already set to true
. I checked dex file from APK and referenced methods number was less than 64k, so project doesn't need to be a multidex one, therefore I set multiDexEnabled
to false
. This solution worked for me.
Or you could keep it simple by doing something like this:
alert(angular.equals({}, $scope.items));
Assuming you have a class such as
>>> class Cls(object):
... foo = 1
... bar = 'hello'
... def func(self):
... return 'call me'
...
>>> obj = Cls()
calling dir
on the object gives you back all the attributes of that object, including python special attributes. Although some object attributes are callable, such as methods.
>>> dir(obj)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'bar', 'foo', 'func']
You can always filter out the special methods by using a list comprehension.
>>> [a for a in dir(obj) if not a.startswith('__')]
['bar', 'foo', 'func']
or if you prefer map/filters.
>>> filter(lambda a: not a.startswith('__'), dir(obj))
['bar', 'foo', 'func']
If you want to filter out the methods, you can use the builtin callable
as a check.
>>> [a for a in dir(obj) if not a.startswith('__') and not callable(getattr(obj, a))]
['bar', 'foo']
You could also inspect the difference between your class and its instance object using.
>>> set(dir(Cls)) - set(dir(object))
set(['__module__', 'bar', 'func', '__dict__', 'foo', '__weakref__'])
I encountered the same error when added http-builder to dependencies.
In my case, I could solve by simply excluding asm like this:
compile('org.codehaus.groovy.modules.http-builder:http-builder:0.7'){
excludes 'xml-apis'
exclude(group:'xerces', module: 'xercesImpl')
excludes 'asm'
}
Create a file called config
inside ~/.ssh
. Inside the file you can add:
Host *
User buck
Or add
Host example
HostName example.net
User buck
The second example will set a username and is hostname specific, while the first example sets a username only. And when you use the second one you don't need to use ssh example.net
; ssh example
will be enough.
I got this in my syncadapter when trying to bulkInsert a large ContentValues[]. I decided to fix it as follows:
try {
count = provider.bulkInsert(uri, contentValueses);
} catch (TransactionTooLarge e) {
int half = contentValueses.length/2;
count += provider.bulkInsert(uri, Arrays.copyOfRange(contentValueses, 0, half));
count += provider.bulkInsert(uri, Arrays.copyOfRange(contentValueses, half, contentValueses.length));
}
MimeTypeMap
may not recognize some file extensions like flv,mpeg,3gpp,cpp. So you need to think how to expand the MimeTypeMap for maintaining your code. Here is such an example.
Plus, here is a complete list of mime types
http: //www.sitepoint.com/web-foundations/mime-types-complete-list/
Use the StringFormat
property (or ContentStringFormat
on ContentControl
and its derivatives, e.g. Label
).
<TextBlock Text="{Binding Date, StringFormat={}{0:d}}" />
Note the {}
prior to the standard String.Format
positional argument notation allows the braces to be escaped in the markup extension language.
SELECCT TO_BASE64(blobfield)
FROM the Table
worked for me.
The CAST(blobfield AS CHAR(10000) CHARACTER SET utf8) and CAST(blobfield AS CHAR(10000) CHARACTER SET utf16) did not show me the text value I wanted to get.
<a href="#anchor">Click me!</a>
<div style="margin-top: -100px; padding-top: 100px;" id="anchor"></div>
<p>I should be 100px below where I currently am!</p>
If I understand your question correctly, then you probably want a density estimate along with the histogram:
X <- c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4))
hist(X, prob=TRUE) # prob=TRUE for probabilities not counts
lines(density(X)) # add a density estimate with defaults
lines(density(X, adjust=2), lty="dotted") # add another "smoother" density
Edit a long while later:
Here is a slightly more dressed-up version:
X <- c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4))
hist(X, prob=TRUE, col="grey")# prob=TRUE for probabilities not counts
lines(density(X), col="blue", lwd=2) # add a density estimate with defaults
lines(density(X, adjust=2), lty="dotted", col="darkgreen", lwd=2)
along with the graph it produces:
File names under OS X are not case sensitive (by default). This is more of an OS problem than a Git problem. If you remove and readd the file, you should get what you want, or rename it to something else and then rename it back.
Make sure you don't include extension of the resource, nor path to it. It's only the resource file name.
PictureBoxName.Image = My.Resources.ResourceManager.GetObject("object_name")
This was a really silly one for me. Adding this here as it's one of the more popular threads on svc 404 issues.
I had in my Project Settings' \ Web \ Project URL, pasted:
http://blah.webservice.local.blahblah.com/Blah.svc
And for some unknown reason (having done this a thousand times) didn't spot straight away that the name of the .svc file was at the end.
DOH!
I had just pasted the address from my WCF test client and hadn't checked it sufficiently. What this did in the background was create an IIS application at the .svc address and I was getting nothing out of IIS. I couldn't work out how I couldn't even hit the .svc file.
Simple fix, obviously, just remove the application in IIS and change the project URL.
After almost 20 years at this, you can still make schoolboy errors / rookie mistakes. Hope this helps someone.
As an option you can initially create Null-able column, then update your table column with valid not null values and finally ALTER column to set NOT NULL constraint:
ALTER TABLE MY_TABLE ADD STAGE INT NULL
GO
UPDATE MY_TABLE SET <a valid not null values for your column>
GO
ALTER TABLE MY_TABLE ALTER COLUMN STAGE INT NOT NULL
GO
Another option is to specify correct default value for your column:
ALTER TABLE MY_TABLE ADD STAGE INT NOT NULL DEFAULT '0'
UPD: Please note that answer above contains GO
which is a must when you run this code on Microsoft SQL server. If you want to perform the same operation on Oracle or MySQL you need to use semicolon ;
like that:
ALTER TABLE MY_TABLE ADD STAGE INT NULL;
UPDATE MY_TABLE SET <a valid not null values for your column>;
ALTER TABLE MY_TABLE ALTER COLUMN STAGE INT NOT NULL;
The trick here is defining "reverse". One can modify the list in place, create a copy in reverse order, or create a view in reversed order.
The simplest way, intuitively speaking, is Collections.reverse
:
Collections.reverse(myList);
This method modifies the list in place. That is, Collections.reverse
takes the list and overwrites its elements, leaving no unreversed copy behind. This is suitable for some use cases, but not for others; furthermore, it assumes the list is modifiable. If this is acceptable, we're good.
If not, one could create a copy in reverse order:
static <T> List<T> reverse(final List<T> list) {
final List<T> result = new ArrayList<>(list);
Collections.reverse(result);
return result;
}
This approach works, but requires iterating over the list twice. The copy constructor (new ArrayList<>(list)
) iterates over the list, and so does Collections.reverse
. We can rewrite this method to iterate only once, if we're so inclined:
static <T> List<T> reverse(final List<T> list) {
final int size = list.size();
final int last = size - 1;
// create a new list, with exactly enough initial capacity to hold the (reversed) list
final List<T> result = new ArrayList<>(size);
// iterate through the list in reverse order and append to the result
for (int i = last; i >= 0; --i) {
final T element = list.get(i);
result.add(element);
}
// result now holds a reversed copy of the original list
return result;
}
This is more efficient, but also more verbose.
Alternatively, we can rewrite the above to use Java 8's stream
API, which some people find more concise and legible than the above:
static <T> List<T> reverse(final List<T> list) {
final int last = list.size() - 1;
return IntStream.rangeClosed(0, last) // a stream of all valid indexes into the list
.map(i -> (last - i)) // reverse order
.mapToObj(list::get) // map each index to a list element
.collect(Collectors.toList()); // wrap them up in a list
}
nb. that Collectors.toList()
makes very few guarantees about the result list. If you want to ensure the result comes back as an ArrayList, use Collectors.toCollection(ArrayList::new)
instead.
The third option is to create a view in reversed order. This is a more complicated solution, and worthy of further reading/its own question. Guava's Lists#reverse method is a viable starting point.
Choosing a "simplest" implementation is left as an exercise for the reader.
You should put all your words into some kind of Collection or List and then call it like this:
var searchFor = new List<string>();
searchFor.Add("pineapple");
searchFor.Add("mango");
bool containsAnySearchString = searchFor.Any(word => compareString.Contains(word));
If you need to make a case or culture independent search you should call it like this:
bool containsAnySearchString =
searchFor.Any(word => compareString.IndexOf
(word, StringComparison.InvariantCultureIgnoreCase >= 0);
Many of them has a given a different working answers, and i too got the same lint errors i make it ignore by doing the following with eclipse.
Thats it.
Note that iPhone 6 will use the 320pt (640px) resolution if you have enabled the 'Display Zoom' in iPhone > Settings > Display & Brightness > View.
To change the font name use
"font.face": "Liberation Mono"
in this file, in my case with ST3 Default.sublime-theme
As per the Django Project Skeleton, the proper directory structure that could be followed is :
[projectname]/ <- project root
+-- [projectname]/ <- Django root
¦ +-- __init__.py
¦ +-- settings/
¦ ¦ +-- common.py
¦ ¦ +-- development.py
¦ ¦ +-- i18n.py
¦ ¦ +-- __init__.py
¦ ¦ +-- production.py
¦ +-- urls.py
¦ +-- wsgi.py
+-- apps/
¦ +-- __init__.py
+-- configs/
¦ +-- apache2_vhost.sample
¦ +-- README
+-- doc/
¦ +-- Makefile
¦ +-- source/
¦ +-- *snap*
+-- manage.py
+-- README.rst
+-- run/
¦ +-- media/
¦ ¦ +-- README
¦ +-- README
¦ +-- static/
¦ +-- README
+-- static/
¦ +-- README
+-- templates/
+-- base.html
+-- core
¦ +-- login.html
+-- README
Refer https://django-project-skeleton.readthedocs.io/en/latest/structure.html for the latest directory structure.
Given that your strings are all fixed-length (presumably at compile-time?), you can do the following:
char (*orderedIds)[ID_LEN+1]
= malloc(variableNumberOfElements * sizeof(*orderedIds));
// Clear-up
free(orderedIds);
A more cumbersome, but more general, solution, is to assign an array of pointers, and psuedo-initialising them to point at elements of a raw backing array:
char *raw = malloc(variableNumberOfElements * (ID_LEN + 1));
char **orderedIds = malloc(sizeof(*orderedIds) * variableNumberOfElements);
// Set each pointer to the start of its corresponding section of the raw buffer.
for (i = 0; i < variableNumberOfElements; i++)
{
orderedIds[i] = &raw[i * (ID_LEN+1)];
}
...
// Clear-up pointer array
free(orderedIds);
// Clear-up raw array
free(raw);
If you want to run a .bat file in full screen, right click on the "example.bat" and click create shortcut, then right click on the shortcut and click properties, then click layout, in layout you can adjust your file to the screen manually, however you can only run it this way if you use the shortcut. You can also change font size by clicking font instead of layout, select lucida and adjust the font size then click apply
Basically you just have to map the procedure to the entity using Stored Procedure Mapping.
Once mapped, you use the regular method for adding an item in EF, and it will use your stored procedure instead.
Please see: This Link for a walkthrough. The result will be adding an entity like so (which will actually use your stored procedure)
using (var ctx = new SchoolDBEntities())
{
Student stud = new Student();
stud.StudentName = "New sp student";
stud.StandardId = 262;
ctx.Students.Add(stud);
ctx.SaveChanges();
}
As stated in problem, to solve this error you MUST use correct annotations. In above problem, @NotBlank
or @NotEmpty
annotation must be applied on any String field only.
To validate long type field, use annotation @NotNull
.
ROBOCOPY works great for me. Originally suggested my Iman. But instead of moving the files/folders to a temporary directory then deleting the contents of the temporary folder, move the files to the trash!!!
This is is a few lines of my backup batch file for example:
SET FilesToClean1=C:\Users\pauls12\Temp
SET FilesToClean2=C:\Users\pauls12\Desktop\1616 - Champlain\Engineering\CAD\Backups
SET RecycleBin=C:\$Recycle.Bin\S-1-5-21-1480896384-1411656790-2242726676-748474
robocopy "%FilesToClean1%" "%RecycleBin%" /mov /MINLAD:15 /XA:SH /NC /NDL /NJH /NS /NP /NJS
robocopy "%FilesToClean2%" "%RecycleBin%" /mov /MINLAD:30 /XA:SH /NC /NDL /NJH /NS /NP /NJS
It cleans anything older than 15 days out of my 'Temp' folder and 30 days for anything in my AutoCAD backup folder. I use variables because the line can get quite long and I can reuse them for other locations. You just need to find the dos path to your recycle bin associated with your login.
This is on a work computer for me and it works. I understand that some of you may have more restrictive rights but give it a try anyway;) Search Google for explanations on the ROBOCOPY parameters.
Cheers!
I've tried the code from above and made my own shadow which is little bit closer to what I am trying to achieve. Maybe it will help others too.
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<layer-list>
<item android:left="5dp" android:top="5dp">
<shape>
<corners android:radius="3dp" />
<gradient
android:angle="315"
android:endColor="@android:color/transparent"
android:startColor="@android:color/black"
android:type="radial"
android:centerX="0.55"
android:centerY="0"
android:gradientRadius="300"/>
<padding android:bottom="1dp" android:left="0dp" android:right="3dp" android:top="0dp" />
</shape>
</item>
<item android:bottom="2dp" android:left="3dp">
<shape>
<corners android:radius="1dp" />
<solid android:color="@color/colorPrimary" />
</shape>
</item>
</layer-list>
</item>
</selector>
A simple answer would be : No, it doesn't
Explanation : According to the definition of unique constraints (SQL-92)
A unique constraint is satisfied if and only if no two rows in a table have the same non-null values in the unique columns
This statement can have two interpretations as :
NULL
and NULL
is not allowedNULL
and NULL
is fine, but StackOverflow
and StackOverflow
is not allowedSince MySQL follows second interpretation, multiple NULL
values are allowed in UNIQUE
constraint column. Second, if you would try to understand the concept of NULL
in SQL, you will find that two NULL
values can be compared at all since NULL
in SQL refers to unavailable or unassigned value (you can't compare nothing with nothing). Now, if you are not allowing multiple NULL
values in UNIQUE
constraint column, you are contracting the meaning of NULL
in SQL. I would summarise my answer by saying :
MySQL supports UNIQUE constraint but not on the cost of ignoring NULL values
Type "ctor" and press the TAB key twice this will add the default constructor automatically
In Java 8:
Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.forEach((key,value) -> {
System.out.println(key + " -> " + value);
});
This maybe too late but No one provided a clear explanation of how the algorithm works
The idea of Dijkstra is simple, let me show this with the following pseudocode.
Dijkstra partitions all nodes into two distinct sets. Unsettled and settled. Initially all nodes are in the unsettled set, e.g. they must be still evaluated.
At first only the source node is put in the set of settledNodes. A specific node will be moved to the settled set if the shortest path from the source to a particular node has been found.
The algorithm runs until the unsettledNodes set is empty. In each iteration it selects the node with the lowest distance to the source node out of the unsettledNodes set. E.g. It reads all edges which are outgoing from the source and evaluates each destination node from these edges which are not yet settled.
If the known distance from the source to this node can be reduced when the selected edge is used, the distance is updated and the node is added to the nodes which need evaluation.
Please note that Dijkstra also determines the pre-successor of each node on its way to the source. I left that out of the pseudo code to simplify it.
Credits to Lars Vogel
From your service method:
function serviceMethod() {
return $timeout(function() {
return {
property: 'value'
};
}, 1000);
}
And in your controller:
serviceName
.serviceMethod()
.then(function(data){
//handle the success condition here
var x = data.property
});
You can check your respone content, just console.log it and you will see whitch property have a status code. If you do not understand jsons, please refer to the video: https://www.youtube.com/watch?v=Bv_5Zv5c-Ts
It explains very basic knowledge that let you feel more comfortable with javascript.
You can do it with shorter version of ajax request, please see code above:
$.get("example.url.com", function(data) {
console.log(data);
}).done(function() {
// TO DO ON DONE
}).fail(function(data, textStatus, xhr) {
//This shows status code eg. 403
console.log("error", data.status);
//This shows status message eg. Forbidden
console.log("STATUS: "+xhr);
}).always(function() {
//TO-DO after fail/done request.
console.log("ended");
});
Example console output:
error 403
STATUS: Forbidden
ended
This (mysql_connect, mysql_...) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
(ref: http://php.net/manual/en/function.mysql-connect.php)
Object Oriented:
$mysqli = new mysqli("host", "user", "password");
$mysqli->select_db("db");
Procedural:
$link = mysqli_connect("host","user","password") or die(mysqli_error($link));
mysqli_select_db($link, "db");
Simple solution:
8080
:`sudo lsof -i:8080`
`kill $PID`
PID is got from step 1's output.
Aloha from 2018. Unfortunately, I don't have anything cool or futuristic to share with you.
I did however want to point out to those who have commented that the jQuery load()
method isn't working in the present are probably trying to use the method with local files without running a local web server. Doing so will throw the above mentioned "cross origin" error, which specifies that cross origin requests such as that made by the load method are only supported for protocol schemes like http
, data
, or https
. (I'm assuming that you're not making an actual cross-origin request, i.e the header.html file is actually on the same domain as the page you're requesting it from)
So, if the accepted answer above isn't working for you, please make sure you're running a web server. The quickest and simplest way to do that if you're in a rush (and using a Mac, which has Python pre-installed) would be to spin up a simple Python http server. You can see how easy it is to do that here.
I hope this helps!
In most cases, using __dict__
or dir()
will get you the info you're wanting. If you should happen to need more details, the standard library includes the inspect module, which allows you to get some impressive amount of detail. Some of the real nuggests of info include:
If you're just looking for "what attribute values does my object have?", then dir()
and __dict__
are probably sufficient. If you're really looking to dig into the current state of arbitrary objects (keeping in mind that in python almost everything is an object), then inspect
is worthy of consideration.
To close a windows form (System.Windows.Forms.Form) when one of its button is clicked: in Visual Studio, open the form in the designer, right click on the button and open its property page, then select the field DialogResult an set it to OK or the appropriate value.
Ids are meant to be unique, and never use an id that starts with a number, use data-attributes instead to set the target like so :
<div id="searchbycharacter">
<a class="searchbychar" href="#" data-target="numeric">0-9 |</a>
<a class="searchbychar" href="#" data-target="A"> A |</a>
<a class="searchbychar" href="#" data-target="B"> B |</a>
<a class="searchbychar" href="#" data-target="C"> C |</a>
... Untill Z
</div>
As for the jquery :
$(document).on('click','.searchbychar', function(event) {
event.preventDefault();
var target = "#" + this.getAttribute('data-target');
$('html, body').animate({
scrollTop: $(target).offset().top
}, 2000);
});
The legend is part of the default options of the ChartJs library. So you do not need to explicitly add it as an option.
The library generates the HTML. It is merely a matter of adding that to the your page. For example, add it to the innerHTML of a given DIV. (Edit the default options if you are editing the colors, etc)
<div>
<canvas id="chartDiv" height="400" width="600"></canvas>
<div id="legendDiv"></div>
</div>
<script>
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "The Flash's Speed",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
},
{
label: "Superman's Speed",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}
]
};
var myLineChart = new Chart(document.getElementById("chartDiv").getContext("2d")).Line(data);
document.getElementById("legendDiv").innerHTML = myLineChart.generateLegend();
</script>
I only have half the answer, but I hope that it is useful as it adds unicode (utf-8) support
//decimal to unicode character
function unichr($dec) {
if ($dec < 128) {
$utf = chr($dec);
} else if ($dec < 2048) {
$utf = chr(192 + (($dec - ($dec % 64)) / 64));
$utf .= chr(128 + ($dec % 64));
} else {
$utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
$utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
$utf .= chr(128 + ($dec % 64));
}
return $utf;
}
To string
var_dump(unichr(hexdec('e641')));
Source: http://www.php.net/manual/en/function.chr.php#Hcom55978
in my case, the tortoise icon not showing at all, I tried this and solved my problem :
(the point is to place all tortoise folder at top)
What about the Checked event? Combine that with AttachedCommandBehaviors or something similar, and a DelegateCommand to get a function fired in your viewmodel everytime that event is called.
Take a look at my jquery videoBG plugin
http://syddev.com/jquery.videoBG/
Make any HTML5 video a site background... has an image fallback for browsers that don't support html5
Really easy to use
Let me know if you need any help.
Here is the way I executed the program without environment variable configured.
Java file execution procedure: After you saved a file MyFirstJavaProgram.java
Enter the whole Path of "Javac" followed by java file For executing output Path of followed by comment <-cp> followed by followed by
C:\Program Files\Java\jdk1.8.0_101\bin>javac C:\Sample\MyFirstJavaProgram2.java C:\Program Files\Java\jdk1.8.0_101\bin>java -cp C:\Sample MyFirstJavaProgram2 Hello World
What you are saying is to use the method like this:
globvar = 5
def f():
var = globvar
print(var)
f() # Prints 5
But the better way is to use the global variable like this:
globvar = 5
def f():
global globvar
print(globvar)
f() #prints 5
Both give the same output.
$("a[href*=ABC]").addClass('selected');
If you are getting io.set not a function
or io.origins not a function
, you can try such notation:
import express from 'express';
import { Server } from 'socket.io';
const app = express();
const server = app.listen(3000);
const io = new Server(server, { cors: { origin: '*' } });
Your data types are mismatched when you are retrieving the field values.
Also check how you store your enums, default is ORDINAL (numeric value stored in database), but STRING (name of enum stored in database) is also an option. Make sure the Entity in your code and the Model in your database are exactly the same.
I had an enum mismatch. It was set to default (ORDINAL) but the database model was expecting a string VARCHAR2(100char). Solution:
@Enumerated(EnumType.STRING)
From Auth0.com
Token-Based Authentication, relies on a signed token that is sent to the server on each request.
What are the benefits of using a token-based approach?
Cross-domain / CORS: cookies + CORS don't play well across different domains. A token-based approach allows you to make AJAX calls to any server, on any domain because you use an HTTP header to transmit the user information.
Stateless (a.k.a. Server side scalability): there is no need to keep a session store, the token is a self-contained entity that conveys all the user information. The rest of the state lives in cookies or local storage on the client side.
CDN: you can serve all the assets of your app from a CDN (e.g. javascript, HTML, images, etc.), and your server side is just the API.
Decoupling: you are not tied to any particular authentication scheme. The token might be generated anywhere, hence your API can be called from anywhere with a single way of authenticating those calls.
Mobile ready: when you start working on a native platform (iOS, Android, Windows 8, etc.) cookies are not ideal when consuming a token-based approach simplifies this a lot.
CSRF: since you are not relying on cookies, you don't need to protect against cross site requests (e.g. it would not be possible to sib your site, generate a POST request and re-use the existing authentication cookie because there will be none).
Performance: we are not presenting any hard perf benchmarks here, but a network roundtrip (e.g. finding a session on database) is likely to take more time than calculating an HMACSHA256 to validate a token and parsing its contents.
You can't specify an exact sleep time in Windows. You need a real-time OS for that. The best you can do is specify a minimum sleep time. Then it's up to the scheduler to wake up your thread after that. And never call .Sleep()
on the GUI thread.
I ran into this problem in a slightly different way from the other answers here.
If I simply created a new xib file, added a UIViewController to it in Interface Builder, and set that UIViewController's custom class to my view controller, that resulted in the "view outlet was not set" crash. The other solutions here say to control-drag the view outlet to the View, but for me the view outlet was greyed out and I couldn't control-drag it.
I figured out that my mistake was in adding a UIViewController in Interface Builder. Instead, I had to add a UIView, and set the Custom Class of the File's Owner to my view controller. Then I could control-drag the view outlet of the File's Owner to my new view UIView and everything worked as it should.
you want to work onMessageReceived(RemoteMessage remoteMessage) in background send only data part notification part this:
"data": "image": "", "message": "Firebase Push Message Using API",
"AnotherActivity": "True", "to" : "device id Or Device token"
By this onMessageRecivied is call background and foreground no need to handle notification using notification tray on your launcher activity. Handle data payload in using this:
public void onMessageReceived(RemoteMessage remoteMessage)
if (remoteMessage.getData().size() > 0)
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
Python uses the ;
as a separator, not a terminator. You can also use them at the end of a line, which makes them look like a statement terminator, but this is legal only because blank statements are legal in Python -- a line that contains a semicolon at the end is two statements, the second one blank.
You should use the key() function.
key($array)
should return the current key.
If you need the position of the current key:
array_search($key, array_keys($array));
Ajay Kumar offers the simplest echo +$numString; I use these:
echo round($val = "0005");
echo $val = 0005;
//both output 5
echo round($val = 00000648370000075845);
echo round($val = "00000648370000075845");
//output 648370000075845, no need to care about the other zeroes in the number
//like with regex or comparative functions. Works w/wo single/double quotes
Actually any math function will take the number from the "string" and treat it like so. It's much simpler than any regex or comparative functions. I saw that in php.net, don't remember where.
The answer is: you can't only through sms, i have tried that approach before.
You could fetch the base station IDs, but this won't help you a lot without the location of the base station itself and this informations are really hard to retrieve from the providers.
I have looked through the 3 apps you have listed in your question:
If it is possible to change the sequence of the lines you could do:
^(.*\r?\n)\1+
How it works: The sorting puts the duplicates behind each other. The find matches a line ^(.*\r?\n)
and captures the line in \1
then it continues and tries to find \1
one or more times (+
) behind the first match. Such a block of duplicates (if it exists) is replaced with nothing.
The \r?\n
should deal nicely with Windows and Unix lineendings.
There's a way to exclude specific auto-configuration classes using @SpringBootApplication
annotation.
@Import(MyPersistenceConfiguration.class)
@SpringBootApplication(exclude = {
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
HibernateJpaAutoConfiguration.class})
public class MySpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApplication.class, args);
}
}
@SpringBootApplication#exclude
attribute is an alias for @EnableAutoConfiguration#exclude
attribute and I find it rather handy and useful.
I added @Import(MyPersistenceConfiguration.class)
to the example to demonstrate how you can apply your custom database configuration.
file = request.FILES['filename']
file.name # Gives name
file.content_type # Gives Content type text/html etc
file.size # Gives file's size in byte
file.read() # Reads file
I dont know why but it worked for me. If you have comments like
//Comment
Then it gives this error. To fix this do
/*Comment*/
Doesn't make sense but it worked for me.
Loki has both a Factory Method and an Abstract Factory. Both are documented (extensively) in Modern C++ Design, by Andei Alexandrescu. The factory method is probably closer to what you seem to be after, though it's still a bit different (at least if memory serves, it requires you to register a type before the factory can create objects of that type).
For Windows
A Way to get all the pids of programs on your computer without downloading any modules:
import os
pids = []
a = os.popen("tasklist").readlines()
for x in a:
try:
pids.append(int(x[29:34]))
except:
pass
for each in pids:
print(each)
If you just wanted one program or all programs with the same name and you wanted to kill the process or something:
import os, sys, win32api
tasklistrl = os.popen("tasklist").readlines()
tasklistr = os.popen("tasklist").read()
print(tasklistr)
def kill(process):
process_exists_forsure = False
gotpid = False
for examine in tasklistrl:
if process == examine[0:len(process)]:
process_exists_forsure = True
if process_exists_forsure:
print("That process exists.")
else:
print("That process does not exist.")
raw_input()
sys.exit()
for getpid in tasklistrl:
if process == getpid[0:len(process)]:
pid = int(getpid[29:34])
gotpid = True
try:
handle = win32api.OpenProcess(1, False, pid)
win32api.TerminateProcess(handle, 0)
win32api.CloseHandle(handle)
print("Successfully killed process %s on pid %d." % (getpid[0:len(prompt)], pid))
except win32api.error as err:
print(err)
raw_input()
sys.exit()
if not gotpid:
print("Could not get process pid.")
raw_input()
sys.exit()
raw_input()
sys.exit()
prompt = raw_input("Which process would you like to kill? ")
kill(prompt)
That was just a paste of my process kill program I could make it a whole lot better but it is okay.
You can use:
const sha1 = require('sha1');
const crypt = sha1('Text');
console.log(crypt);
For install:
sudo npm install -g sha1
npm install sha1 --save
If you KNOW that a function returns a promise, i suggest using the new async/await features in JavaScript. It makes the syntax look synchronous but work asynchronously. When you add the async
keyword to a function, it allows you to await
promises in that scope:
async function ace() {
var r = await new Promise((resolve, reject) => {
resolve(true)
});
console.log(r); // true
}
if a function does not return a promise, i recommend wrapping it in a new promise that you define, then resolve the data that you want:
function ajax_call(url, method) {
return new Promise((resolve, reject) => {
fetch(url, { method })
.then(resp => resp.json())
.then(json => { resolve(json); })
});
}
async function your_function() {
var json = await ajax_call('www.api-example.com/some_data', 'GET');
console.log(json); // { status: 200, data: ... }
}
Bottom line: leverage the power of Promises.
Mongo is NoSQL Database.
If you don't want to use any ORM for your data models then you can also use native driver mongo.js: https://github.com/mongodb/node-mongodb-native.
Mongoose is one of the orm's who give us functionality to access the mongo data with easily understandable queries.
Mongoose plays as a role of abstraction over your database model.
If the first item is to be used as a placeholder (empty value) and your select is required
then you can use the :invalid
pseudo-class to target it.
select {_x000D_
-webkit-appearance: menulist-button;_x000D_
color: black;_x000D_
}_x000D_
_x000D_
select:invalid {_x000D_
color: green;_x000D_
}
_x000D_
<select required>_x000D_
<option value="">Item1</option>_x000D_
<option value="Item2">Item2</option>_x000D_
<option value="Item3">Item3</option>_x000D_
</select>
_x000D_
\xe2 is the '-' character, it appears in some copy and paste it uses a different equal looking '-' that causes encoding errors. Replace the '-'(from copy paste) with the correct '-' (from you keyboard button).
In case you don't want to change your current working directory, it might be easier to run extract command in a subshell like this.
mkdir -p "/path/to/target-dir"
(cd "/path/to/target-dir" && exec jar -xf "/path/to/your/war-file.war")
You can then execute this script from any working directory.
[ Thanks to David Schmitt for the subshell trick ]
If you restructured your date format into YYYY/MM/DD then you can use this simple string ordering to achieve the formating you need.
Alternatively, using the SUBSTR(store_name,start,length) command you should be able to restructure the sorting term into the above format
perhaps using the following
SELECT *
FROM vw_view
ORDER BY SUBSTR(EventDate,6,4) + SUBSTR(EventDate, 0, 5) DESC
public static string TruncateLongString(this string str, int maxLength)
{
if (string.IsNullOrEmpty(str)) return str;
return str.Substring(0, Math.Min(str.Length, maxLength));
}
If you are using Storyboards you can go to Attributes Inspector
of the ViewController's Navigation Item
(click on Navigation Bar
) and set the Back Button
property to " " (one space character). This will set the Back Button title to one space character, leaving the chevron visible. No need to mess with code.
Note that this will set Back Button
title for the Back Button that will segue to this View Controller from the one that was pushed on top of it, not for the Back Button
that will be displayed inside this Controller!
To account for leading and trailing whitespace, you probably want to use normalize-space()
//div[contains(@class, 'Caption') and normalize-space(.)='Model saved']
and
//div[@id='alertLabel' and normalize-space(.)='Save to server successful']
Note that //div[contains(@class, 'Caption') and normalize-space(.//text())='Model saved']
also works.
2 successive mounts: I guess many posts here might be using two boot2docker, the reason you don't see anything is that you are mounting a directory from boot2docker, not from your host.
You basically need 2 successive mounts:
the first one to mount a directory from your host to your system
the second to mount the new directory from boot2docker to your container like this:
1) Mount local system on boot2docker
sudo mount -t vboxsf hostfolder /boot2dockerfolder
2) Mount boot2docker
file on linux container
docker run -v /boot2dockerfolder:/root/containerfolder -i -t imagename
Then when you ls
inside the containerfolder
you will see the content of your hostfolder
.
Steps:
I solved this by doing the following:
WebServer(ISS)->WebServer->Application Development
add .NET Extensibility 3.5
add .NET Extensibility 4.5
add ASP.NET 4.5
add ISAPI Extensions
add ISAPI Filters
You can automatically do it in Notepad++ (add text at the beginning and/or end of each line) by using one regular expression in Replace (Ctrl+H):
Explanation: Expression $1
in Replace with input denotes all the characters that include the round brackets (.*)
in Find what regular expressin.
Tested, it works.
Hope that helps.
let headers = new Headers({
'Content-Type': 'application/json',
'MyApp-Application': 'AppName',
'Accept': 'application/vnd.ms-excel'
});
let options = new RequestOptions({
headers: headers,
responseType: ResponseContentType.Blob
});
this.http.post(this.urlName + '/services/exportNewUpc', localStorageValue, options)
.subscribe(data => {
if (navigator.appVersion.toString().indexOf('.NET') > 0)
window.navigator.msSaveBlob(data.blob(), "Export_NewUPC-Items_" + this.selectedcategory + "_" + this.retailname +"_Report_"+this.myDate+".xlsx");
else {
var a = document.createElement("a");
a.href = URL.createObjectURL(data.blob());
a.download = "Export_NewUPC-Items_" + this.selectedcategory + "_" + this.retailname +"_Report_"+this.myDate+ ".xlsx";
a.click();
}
this.ui_loader = false;
this.selectedexport = 0;
}, error => {
console.log(error.json());
this.ui_loader = false;
document.getElementById("exceptionerror").click();
});
<script type="text/javascript">var s = '/Controller/Action#11112';if(typeof s == 'string' && /\?*/.test(s)){s = s.replace(/\#.*/gi,'');}document.write(s);</script>
It's more common answer. And can be use with s= document.location.href;
As for your second problem:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python31\lib\pickle.py", line
1365, in load encoding=encoding,
errors=errors).load() EOFError
After you have read the contents of the file, the file pointer will be at the end of the file - there will be no further data to read. You have to rewind the file so that it will be read from the beginning again:
file.seek(0)
What you usually want to do though, is to use a context manager to open the file and read data from it. This way, the file will be automatically closed after the block finishes executing, which will also help you organize your file operations into meaningful chunks.
Finally, cPickle is a faster implementation of the pickle module in C. So:
In [1]: import _pickle as cPickle
In [2]: d = {"a": 1, "b": 2}
In [4]: with open(r"someobject.pickle", "wb") as output_file:
...: cPickle.dump(d, output_file)
...:
# pickle_file will be closed at this point, preventing your from accessing it any further
In [5]: with open(r"someobject.pickle", "rb") as input_file:
...: e = cPickle.load(input_file)
...:
In [7]: print e
------> print(e)
{'a': 1, 'b': 2}
Referring to this link Boolean datatype in Mysql, according to the application usage, if one wants only 0 or 1 to be stored, bit(1) is the better choice.
Make sure the .gitignore does not have a extension!! It can't be .gitignore.txt, in windows just name the file .gitignore. and it will work.
Answering this just in case if someone else like me stumbles upon this post among many that advise use of JavaScripts for changing iframe height to 100%.
I strongly recommend that you see and try this option specified at How do you give iframe 100% height before resorting to a JavaScript based option. The referenced solution works perfectly for me in all of the testing I have done so far. Hope this helps someone.
Many solutions have been posted and I'd like to contribute with mine, which works for a different number of columns in the CSV file. It creates a dictionary with one key per column, and the value for each key is a list with the elements in such column.
input_file = csv.DictReader(open(path_to_csv_file))
csv_dict = {elem: [] for elem in input_file.fieldnames}
for row in input_file:
for key in csv_dict.keys():
csv_dict[key].append(row[key])
You could do many of the given answers, but if you just want to do it to be able to use it with strcpy
, then you could do the following:
...
strcpy( ... , (char[2]) { (char) c, '\0' } );
...
The (char[2]) { (char) c, '\0' }
part will temporarily generate null-terminated string out of a character c
.
This way you could avoid creating new variables for something that you already have in your hands, provided that you'll only need that single-character string just once.
You typically have to do this in a single syscall, or else you will get a race condition.
This will open for reading and writing, creating the file if necessary.
FILE *fp = fopen("scores.dat", "ab+");
If you want to read it and then write a new version from scratch, then do it as two steps.
FILE *fp = fopen("scores.dat", "rb");
if (fp) {
read_scores(fp);
}
// Later...
// truncates the file
FILE *fp = fopen("scores.dat", "wb");
if (!fp)
error();
write_scores(fp);
Go to MySQL workbench and log to the server. There is a field called Server Status under MANAGEMENT. Click on Server Status and find out the version.
Or else go to following location and open cmd -> C:\Windows\System32\cmd.exe. Then hit the command -> mysql -V
I made a fairly complete library of 3D mathematics for Python{2,3}. It still does not use Cython, but relies heavily on the efficiency of numpy. You can find it here with pip:
python[3] -m pip install math3d
Or have a look at my gitweb http://git.automatics.dyndns.dk/?p=pymath3d.git and now also on github: https://github.com/mortlind/pymath3d .
Once installed, in python you may create the orientation object which can rotate vectors, or be part of transform objects. E.g. the following code snippet composes an orientation that represents a rotation of 1 rad around the axis [1,2,3], applies it to the vector [4,5,6], and prints the result:
import math3d as m3d
r = m3d.Orientation.new_axis_angle([1,2,3], 1)
v = m3d.Vector(4,5,6)
print(r * v)
The output would be
<Vector: (2.53727, 6.15234, 5.71935)>
This is more efficient, by a factor of approximately four, as far as I can time it, than the oneliner using scipy posted by B. M. above. However, it requires installation of my math3d package.
You can use org.apache.commons.io.IOUtils.copy
to copy the contents of the InputStream to a byte array, and then repeatedly read from the byte array using a ByteArrayInputStream. E.g.:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
org.apache.commons.io.IOUtils.copy(in, baos);
byte[] bytes = baos.toByteArray();
// either
while (needToReadAgain) {
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
yourReadMethodHere(bais);
}
// or
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
while (needToReadAgain) {
bais.reset();
yourReadMethodHere(bais);
}
I was having the same issue and this works excellently.
Private Sub DataGridView17_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView17.CellFormatting
'Display complete contents in tooltip even though column display cuts off part of it.
DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).ToolTipText = DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
End Sub
One lightweight trick is to make a redirect in your urls.py
file, e.g. add a view like so:
from django.views.generic.base import RedirectView
favicon_view = RedirectView.as_view(url='/static/favicon.ico', permanent=True)
urlpatterns = [
...
re_path(r'^favicon\.ico$', favicon_view),
...
]
This works well as an easy trick for getting favicons working when you don't really have other static content to host.
If someone still having this problem.Try to use instead of ovverriding
public void OnActionExecuting(ActionExecutingContext context)
{
try
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
if (!HttpContext.Current.Response.IsRequestBeingRedirected)
{
context.Result = new RedirectToRouteResult(
new RouteValueDictionary { { "controller", "Login" }, { "action", "Index" } });
}
}
}
catch (Exception ex)
{
new RouteValueDictionary { { "controller", "Login" }, { "action", "Index" } });
}
}
To both check if it exists and create if it doesn't, including intermediaries:
QDir dir("path/to/dir");
if (!dir.exists())
dir.mkpath(".");
Older IE and Firefox browsers attach the scrollbar to the documentElement
, or what would be the <html>
tag in HTML.
All other browsers attach the scrollbar to document.body
, or what would be the <body>
tag in HTML.
The correct solution would be to check which one to use, depending on browser
var doc = document.documentElement.clientHeight ? document.documentElement : document.body;
var s = $(doc).scrollTop();
jQuery does make this a little easier, when passing in either window
or document
jQuery's scrollTop
does a similar check and figures it out, so either of these should work cross-browser
var s = $(document).scrollTop();
or
var s = $(window).scrollTop();
Description: Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element.
...nothing that works for my div, just the full page
If it's for a DIV, you'd have to target the element that has the scrollbar attached, to get the scrolled amount
$('div').scrollTop();
If you need to get the elements distance from the top of the document, you can also do
$('div').offset().top
Correct answer is simply:
SELECT a.group_id
FROM a
LEFT JOIN b ON a.group_id=b.group_id and b.user_id = 4
where b.user_id is null
and a.keyword like '%keyword%'
Here we are checking user_id = 4
(your user id from the session). Since we have it in the join criteria, it will return null values for any row in table b that does not match the criteria - ie, any group that that user_id is NOT in.
From there, all we need to do is filter for the null values, and we have all the groups that your user is not in.
If you don't have bs-config.json
, you can change the port inside the lite-server module. Go to node_modules/lite-server/lib/config-defaults.js
in your project, then add the port in "modules.export" like this.
module.export {
port :8000, // to any available port
...
}
Then you can restart the server.
#include <iostream>
using namespace std;
class matrix
{
int a[10][10],b[10][10],c[10][10],x,y,i,j;
public :
void degerler();
void ters();
};
void matrix::degerler()
{
cout << "Satirlari giriniz: "; cin >> x;
cout << "Sütunlari giriniz: "; cin >> y;
cout << "Ilk matris elamanlarini giriniz:\n\n";
for (i=1; i<=x; i++)
{
for (j=1; j<=y; j++)
{
cin >> a[i][j];
}
}
cout << "Ikinci matris elamanlarini giriniz:\n\n";
for (i=1; i<=x; i++)
{
for (j=1; j<=y; j++)
{
cin >> b[i][j];
}
}
}
void matrix::ters()
{
cout << "matrisin tersi\n";
for (i=1; i<=x; i++)
{
for (j=1; j<=y; j++)
{
if(i==j)
{
b[i][j]=1;
}
else
b[i][j]=0;
}
}
float d,k;
for (i=1; i<=x; i++)
{
d=a[i][j];
for (j=1; j<=y; j++)
{
a[i][j]=a[i][j]/d;
b[i][j]=b[i][j]/d;
}
for (int h=0; h<x; h++)
{
if(h!=i)
{
k=a[h][j];
for (j=1; j<=y; j++)
{
a[h][j]=a[h][j]-(a[i][j]*k);
b[h][j]=b[h][j]-(b[i][j]*k);
}
}
count << a[i][j] << "";
}
count << endl;
}
}
int main()
{
int secim;
char ch;
matrix m;
m.degerler();
do
{
cout << "seçiminizi giriniz\n";
cout << " 1. matrisin tersi\n";
cin >> secim;
switch (secim)
{
case 1:
m.ters();
break;
}
cout << "\nBaska bir sey yap/n?";
cin >> ch;
}
while (ch!= 'n');
cout << "\n";
return 0;
}
Adding to Jim's elaborate answer:
Check the typing
module -- this module supports type hints as specified by PEP 484.
For example, the function below takes and returns values of type str
and is annotated as follows:
def greeting(name: str) -> str:
return 'Hello ' + name
The typing
module also supports:
You have declared an array that can store 8 elements not 9.
this.posStatus = new int[8];
It means postStatus will contain 8 elements from index 0 to 7.
Posting in awesome thread:
var d = new Date(parseInt('/Date(1224043200000)/'.slice(6, -2)));
alert('' + (1 + d.getMonth()) + '/' + d.getDate() + '/' + d.getFullYear().toString().slice(-2));
Just as an FYI....
select * from sys.types where system_type_id = 231
gives you two rows.
(i'm not sure what this means yet but i'm 100% sure it's messing up my code right now)
edit: i guess what it means is that you should join by the user_type_id in this situation (my situation) or possibly both the user_type_id and the system_type_id
name system_type_id user_type_id schema_id principal_id max_length precision scale collation_name is_nullable is_user_defined is_assembly_type default_object_id rule_object_id
nvarchar 231 231 4 NULL 8000 0 0 SQL_Latin1_General_CP1_CI_AS 1 0 0 0 0
sysname 231 256 4 NULL 256 0 0 SQL_Latin1_General_CP1_CI_AS 0 0 0 0 0
create procedure dbo.yyy_test (
@col_one nvarchar(max),
@col_two nvarchar(max) = 'default',
@col_three nvarchar(1),
@col_four nvarchar(1) = 'default',
@col_five nvarchar(128),
@col_six nvarchar(128) = 'default',
@col_seven sysname
)
as begin
select 1
end
This query:
select parm.name AS Parameter,
parm.max_length,
parm.parameter_id
from sys.procedures sp
join sys.parameters parm ON sp.object_id = parm.object_id
where sp.name = 'yyy_test'
order by parm.parameter_id
Yields:
parameter max_length parameter_id
@col_one -1 1
@col_two -1 2
@col_three 2 3
@col_four 2 4
@col_five 256 5
@col_six 256 6
@col_seven 256 7
And This:
select parm.name as parameter,
parm.max_length,
parm.parameter_id,
typ.name as data_type,
typ.system_type_id,
typ.user_type_id,
typ.collation_name,
typ.is_nullable
from sys.procedures sp
join sys.parameters parm ON sp.object_id = parm.object_id
join sys.types typ ON parm.system_type_id = typ.system_type_id
where sp.name = 'yyy_test'
order by parm.parameter_id
Gives You This:
parameter max_length parameter_id data_type system_type_id user_type_id collation_name is_nullable
@col_one -1 1 nvarchar 231 231 SQL_Latin1_General_CP1_CI_AS 1
@col_one -1 1 sysname 231 256 SQL_Latin1_General_CP1_CI_AS 0
@col_two -1 2 nvarchar 231 231 SQL_Latin1_General_CP1_CI_AS 1
@col_two -1 2 sysname 231 256 SQL_Latin1_General_CP1_CI_AS 0
@col_three 2 3 nvarchar 231 231 SQL_Latin1_General_CP1_CI_AS 1
@col_three 2 3 sysname 231 256 SQL_Latin1_General_CP1_CI_AS 0
@col_four 2 4 nvarchar 231 231 SQL_Latin1_General_CP1_CI_AS 1
@col_four 2 4 sysname 231 256 SQL_Latin1_General_CP1_CI_AS 0
@col_five 256 5 nvarchar 231 231 SQL_Latin1_General_CP1_CI_AS 1
@col_five 256 5 sysname 231 256 SQL_Latin1_General_CP1_CI_AS 0
@col_six 256 6 nvarchar 231 231 SQL_Latin1_General_CP1_CI_AS 1
@col_six 256 6 sysname 231 256 SQL_Latin1_General_CP1_CI_AS 0
@col_seven 256 7 nvarchar 231 231 SQL_Latin1_General_CP1_CI_AS 1
@col_seven 256 7 sysname 231 256 SQL_Latin1_General_CP1_CI_AS 0
For Windows OS
For Uppercase CTRL + K + U
For Lowercase CTRL + K + L
I was reading this thread and would like to add information even though it is surely no longer timely for the OP.
BiggerDon above points out the difficulty of rote replacing "North" with "N". A similar problem exists with "Avenue" to "Ave" (e.g. "Avenue of the Americas" becomes "Ave of the Americas": still understandable, but probably not what the OP wants.
The replace() function is entirely context-free, but addresses are not. A complete solution needs to have additional logic to interpret the context correctly, and then apply replace() as needed.
Databases commonly contain addresses, and so I wanted to point out that the generalized version of the OP's problem as applied to addresses within the United States has been addressed (humor!) by the Coding Accuracy Support System (CASS). CASS is a database tool that accepts a U.S. address and completes or corrects it to meet a standard set by the U.S. Postal Service. The Wikipedia entry https://en.wikipedia.org/wiki/Postal_address_verification has the basics, and more information is available at the Post Office: https://ribbs.usps.gov/index.cfm?page=address_info_systems
Try the DATENAME()
function:
select [date_created]
from table
where DATENAME(WEEKDAY, [date_created]) <> 'Saturday'
and DATENAME(WEEKDAY, [date_created]) <> 'Sunday'
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;
using Microsoft.Office.Interop.Excel;
namespace trg.satmap.portal.ParseAgentSkillMapping
{
class ConvertXLStoDT
{
private StringBuilder errorMessages;
public StringBuilder ErrorMessages
{
get { return errorMessages; }
set { errorMessages = value; }
}
public ConvertXLStoDT()
{
ErrorMessages = new StringBuilder();
}
public System.Data.DataTable XLStoDTusingInterOp(string FilePath)
{
#region Excel important Note.
/*
* Excel creates XLS and XLSX files. These files are hard to read in C# programs.
* They are handled with the Microsoft.Office.Interop.Excel assembly.
* This assembly sometimes creates performance issues. Step-by-step instructions are helpful.
*
* Add the Microsoft.Office.Interop.Excel assembly by going to Project -> Add Reference.
*/
#endregion
Microsoft.Office.Interop.Excel.Application excelApp = null;
Microsoft.Office.Interop.Excel.Workbook workbook = null;
System.Data.DataTable dt = new System.Data.DataTable(); //Creating datatable to read the content of the Sheet in File.
try
{
excelApp = new Microsoft.Office.Interop.Excel.Application(); // Initialize a new Excel reader. Must be integrated with an Excel interface object.
//Opening Excel file(myData.xlsx)
workbook = excelApp.Workbooks.Open(FilePath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets.get_Item(1);
Microsoft.Office.Interop.Excel.Range excelRange = ws.UsedRange; //gives the used cells in sheet
ws = null; // now No need of this so should expire.
//Reading Excel file.
object[,] valueArray = (object[,])excelRange.get_Value(Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault);
excelRange = null; // you don't need to do any more Interop. Now No need of this so should expire.
dt = ProcessObjects(valueArray);
}
catch (Exception ex)
{
ErrorMessages.Append(ex.Message);
}
finally
{
#region Clean Up
if (workbook != null)
{
#region Clean Up Close the workbook and release all the memory.
workbook.Close(false, FilePath, Missing.Value);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
#endregion
}
workbook = null;
if (excelApp != null)
{
excelApp.Quit();
}
excelApp = null;
#endregion
}
return (dt);
}
/// <summary>
/// Scan the selected Excel workbook and store the information in the cells
/// for this workbook in an object[,] array. Then, call another method
/// to process the data.
/// </summary>
private void ExcelScanIntenal(Microsoft.Office.Interop.Excel.Workbook workBookIn)
{
//
// Get sheet Count and store the number of sheets.
//
int numSheets = workBookIn.Sheets.Count;
//
// Iterate through the sheets. They are indexed starting at 1.
//
for (int sheetNum = 1; sheetNum < numSheets + 1; sheetNum++)
{
Worksheet sheet = (Worksheet)workBookIn.Sheets[sheetNum];
//
// Take the used range of the sheet. Finally, get an object array of all
// of the cells in the sheet (their values). You can do things with those
// values. See notes about compatibility.
//
Range excelRange = sheet.UsedRange;
object[,] valueArray = (object[,])excelRange.get_Value(XlRangeValueDataType.xlRangeValueDefault);
//
// Do something with the data in the array with a custom method.
//
ProcessObjects(valueArray);
}
}
private System.Data.DataTable ProcessObjects(object[,] valueArray)
{
System.Data.DataTable dt = new System.Data.DataTable();
#region Get the COLUMN names
for (int k = 1; k <= valueArray.GetLength(1); k++)
{
dt.Columns.Add((string)valueArray[1, k]); //add columns to the data table.
}
#endregion
#region Load Excel SHEET DATA into data table
object[] singleDValue = new object[valueArray.GetLength(1)];
//value array first row contains column names. so loop starts from 2 instead of 1
for (int i = 2; i <= valueArray.GetLength(0); i++)
{
for (int j = 0; j < valueArray.GetLength(1); j++)
{
if (valueArray[i, j + 1] != null)
{
singleDValue[j] = valueArray[i, j + 1].ToString();
}
else
{
singleDValue[j] = valueArray[i, j + 1];
}
}
dt.LoadDataRow(singleDValue, System.Data.LoadOption.PreserveChanges);
}
#endregion
return (dt);
}
}
}
do not make headaches for yourself, want a simple, one line solution to add a permanent environment variable (open powershell in elevated mode):
[Environment]::SetEnvironmentVariable("NewEnvVar", "NewEnvValue", "Machine")
close the session and open it again to make things done
in case that u want to modify/change that:
[Environment]::SetEnvironmentVariable("oldEnvVar", "NewEnvValue", "Machine")
in case that u want to delete/remove that:
[Environment]::SetEnvironmentVariable("oldEnvVar", "", "Machine")
Well, you have to set your dialog's height and width before to show this ( dialog.show() )
so, do something like this:
dialog.getWindow().setLayout(width, height);
//then
dialog.show()
For hidden files I had to use the following:
DEL /S /Q /A:H Thumbs.db
I do the following to work out which dependency cannot be found.
Run regedit.exe and navigate to:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion
Create the following:
LogFailures set value to 1 (DWORD)
LogResourceBinds set value to 1 (DWORD)
LogPath (String) set value to C:\FusionLog\
Now run your program and wait for it to raise Could not load file or assembly or one of its dependencies
.
Using explorer, navigate to C:\FusionLog
and there should be a folder containing logs for your program, showing which dependency is missing.
Note: Some people use FUSLOGVW.exe, which is a viewer for these Fusion Logs. On my machine it can be found in multiple places, including:
C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.2 Tools\x64\FUSLOGVW.exe
One way to do it will be to move all the php code above the HTML, copy the result to a variable and then add the result in the <input>
tag.
Try this -
<?php
//Adding the php to the top.
if(isset($_POST['submit']))
{
$value1=$_POST['value1'];
$value2=$_POST['value2'];
$sign=$_POST['sign'];
...
//Adding to $result variable
if($sign=='-') {
$result = $value1-$value2;
}
//Rest of your code...
}
?>
<html>
<!--Rest of your tags...-->
Result:<br><input type"text" name="result" value = "<?php echo (isset($result))?$result:'';?>">
I am new to python and I was already thinking I am too stupid to reproduce the simplest suggestions made here. It turns out, there's a pitfall one should know:
When a python-script is executed from IDLE, some IO-commands seem to behave completely different (as there is actually no terminal window).
Eg. msvcrt.getch is non-blocking and always returns $ff. This has already been reported long ago (see e.g. https://bugs.python.org/issue9290 ) - and it's marked as fixed, somehow the problem seems to persist in current versions of python/IDLE.
So if any of the code posted above doesn't work for you, try running the script manually, and NOT from IDLE.
There is a fairly complete recording demo available at: http://webaudiodemos.appspot.com/AudioRecorder/index.html
It allows you to record audio in the browser, then gives you the option to export and download what you've recorded.
You can view the source of that page to find links to the javascript, but to summarize, there's a Recorder
object that contains an exportWAV
method, and a forceDownload
method.
The good way to get all the members from a group is to, make the DN of the group as the searchDN and pass the "member" as attribute to get in the search function. All of the members of the group can now be found by going through the attribute values returned by the search. The filter can be made generic like (objectclass=*).
try this one out resizeable button
<button type="submit me" style="height: 25px; width: 100px">submit me</button>
If using Postgres or SQLite, you can use the Filter clause to improve readability:
SELECT
COUNT(1) FILTER (WHERE POSITION = 'Manager') AS ManagerCount,
COUNT(1) FILTER (WHERE POSITION = 'Other') AS OtherCount
FROM ...
BigQuery also has Countif
- see the support across different SQL dialects for these features here:
https://modern-sql.com/feature/filter
There are specific suffixes for long
(e.g. 39832L
), float
(e.g. 2.4f
) and double
(e.g. -7.832d
).
If there is no suffix, and it is an integral type (e.g. 5623
), it is assumed to be an int
. If it is not an integral type (e.g. 3.14159
), it is assumed to be a double
.
In all other cases (byte
, short
, char
), you need the cast as there is no specific suffix.
The Java spec allows both upper and lower case suffixes, but the upper case version for long
s is preferred, as the upper case L
is less easy to confuse with a numeral 1
than the lower case l
.
See the JLS section 3.10 for the gory details (see the definition of IntegerTypeSuffix
).
Because Convert.ToInt32
rounds:
Return Value: rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.
...while the cast truncates:
When you convert from a double or float value to an integral type, the value is truncated.
Update: See Jeppe Stig Nielsen's comment below for additional differences (which however do not come into play if score
is a real number as is the case here).
Setting the icon
property when creating the BrowserWindow
only has an effect on Windows and Linux.
To set the icon on OS X, you can use electron-packager and set the icon using the --icon
switch.
It will need to be in .icns format for OS X. There is an online icon converter which can create this file from your .png.
I'm not sure how this example works for older Web browsers but I use this for IE, Firefox and Chrome without an issue:
var iFrameDetection = (window === window.parent) ? false : true;
To add to what others have said, you could also create an alias in your .bashrc or .bash_aliases file:
alias svnlog='svn log -l 30 | less'
or whatever you want as your default
In the POSIX standard, which /bin/sh
is supposed to respect, the command is .
(a single dot), not source
. The source
command is a csh
-ism that has been pulled into bash
.
Try
. $env_name/bin/activate
Or if you must have non-POSIX bash
-isms in your code, use #!/bin/bash
.
In case you use MVC to accomplish it - you will have to do something like this
<form action="/ControllerName/ActionName" method="post">
<a href="javascript:;" onclick="parentNode.submit();"><%=n%></a>
<input type="hidden" name="mess" value=<%=n%>/>
</form>
I just went through some examples here and did not see the MVC one figured it won't hurt to post it.
Then on your Action in the Controller I would just put <HTTPPost>
On the top of it.
I believe if you don't have <HTTPGET>
on the top of it it would still work but explicitly putting it there feels a bit safer.
select * from (
select FName from MyTbl
)
where rownum <= 1;
Items should have an "ID" field, and Tags should have an "ID" field (Primary Key, Clustered).
Then make an intermediate table of ItemID/TagID and put the "Perfect Index" on there.
You may access through tab Id as well, But that id is unique for same page. Here is an example for same
$('#product_detail').tab('show');
In above example #product_details
is nav
tab
id
jQuery:
$('body').on('dragstart drop', function(e){
e.preventDefault();
return false;
});
You can replace the body selector with any other container that children you want to prevent from being dragged and dropped.
Rename your js file to something else temporarily. This is the only thing that worked for me.
The way to install plugins seems to have changed, the previous answers here did not work for me.
The current (checked with 7.8.1) way to install plugins is to install it in a sub folder:
The plugin (in the DLL form) should be placed in the plugins subfolder of the Notepad++ Install Folder, under the subfolder with the same name of plugin binary name without file extension. For example, if the plugin you want to install named myAwesomePlugin.dll, you should install it with the following path: %PROGRAMFILES(x86)%\Notepad++\plugins\myAwesomePlugin\myAwesomePlugin.dll
from https://npp-user-manual.org/docs/plugins/
So PluginManager.dll
goes into PluginManager
sub folder.
Let's say you want to build: u(n+1)=f(u(n)) with u(0)=u0
One solution is to define a simple recursive function:
u0 = ...
def f(x):
...
def u(n):
if n==0: return u0
return f(u(n-1))
Unfortunately, if you want to calculate high values of u, you will run into a stack overflow error.
Another solution is a simple loop:
def u(n):
ux = u0
for i in xrange(n):
ux=f(ux)
return ux
But if you want multiple values of u for different values of n, this is suboptimal. You could cache all values in an array, but you may run into an out of memory error. You may want to use generators instead:
def u(n):
ux = u0
for i in xrange(n):
ux=f(ux)
yield ux
for val in u(1000):
print val
There are many other options, but I guess these are the main ones.
Thats because DataGridView looks for properties of containing objects. For string there is just one property - length. So, you need a wrapper for a string like this
public class StringValue
{
public StringValue(string s)
{
_value = s;
}
public string Value { get { return _value; } set { _value = value; } }
string _value;
}
Then bind List<StringValue>
object to your grid. It works
New syntax has been supported for a while by all modern browsers (starting from Chrome 26, Opera 12.1, IE 10 and Firefox 16): http://caniuse.com/#feat=css-gradients
background: linear-gradient(to bottom, rgba(0, 0, 0, 1), rgba(0, 0, 0, 0));
This renders a gradient, starting from solid black at the top, to fully transparent at the bottom.
If you only want to check if an option is selected, then you do not need to iterate through all options. Just do
if($('#mySelectBox').val()){
// do something
} else {
// do something else
}
Note: If you have an option with value=0 that you want to be selectable, you need to change the if-condition to $('#mySelectBox').val() != null
SQL Logins are defined at the server level, and must be mapped to Users in specific databases.
In SSMS object explorer, under the server you want to modify, expand Security > Logins, then double-click the appropriate user which will bring up the "Login Properties" dialog.
Select User Mapping, which will show all databases on the server, with the ones having an existing mapping selected. From here you can select additional databases (and be sure to select which roles in each database that user should belong to), then click OK to add the mappings.
These mappings can become disconnected after a restore or similar operation. In this case, the user may still exist in the database but is not actually mapped to a login. If that happens, you can run the following to restore the login:
USE {database};
ALTER USER {user} WITH login = {login}
You can also delete the DB user and recreate it from the Login Properties dialog, but any role memberships or other settings would need to be recreated.
For Asp.net Core 2
ViewContext.ModelState["id"].AttemptedValue
For a large database, I am reluctant to lose the size and speed advantages of the numeric representation. I often end up with a database table representing the Enum.
You can enforce database consistency by declaring a foreign key -- although in some cases it might be better to not declare that as a foreign key constraint, which imposes a cost on every transaction. You can ensure consistency by periodically doing a check, at times of your choosing, with:
SELECT reftable.* FROM reftable
LEFT JOIN enumtable ON reftable.enum_ref_id = enumtable.enum_id
WHERE enumtable.enum_id IS NULL;
The other half of this solution is to write some test code that checks that the Java enum and the database enum table have the same contents. That's left as an exercise for the reader.
For a matrix you can use this:
[M,I] = max(A(:))
I is the index of A(:) containing the largest element.
Now, use the ind2sub function to extract the row and column indices of A corresponding to the largest element.
[I_row, I_col] = ind2sub(size(A),I)
For tracking changes to a folder where the folder was moved, I started using:
git rev-list --all --pretty=oneline -- "*/foo/subfoo/*"
This isn't perfect as it will grab other folders with the same name, but if it is unique, then it seems to work.
The exists
keyword can be used in that way, but really it's intended as a way to avoid counting:
--this statement needs to check the entire table
select count(*) from [table] where ...
--this statement is true as soon as one match is found
exists ( select * from [table] where ... )
This is most useful where you have if
conditional statements, as exists
can be a lot quicker than count
.
The in
is best used where you have a static list to pass:
select * from [table]
where [field] in (1, 2, 3)
When you have a table in an in
statement it makes more sense to use a join
, but mostly it shouldn't matter. The query optimiser should return the same plan either way. In some implementations (mostly older, such as Microsoft SQL Server 2000) in
queries will always get a nested join plan, while join
queries will use nested, merge or hash as appropriate. More modern implementations are smarter and can adjust the plan even when in
is used.
I know this is ages old, but upon searching for something similar this morning, and reading up on Atømix' response (as this is what we're aiming on achieving), I found this: http://www.switchonthecode.com/tutorials/using-jquery-slider-to-scroll-a-div.
Just putting that there in case anyone else needs a solution. :)
This issue turned up for me when I was trying to find a similar answer. Consider:
$('.ui-dialog').wrap('<div class="abc" />');
$('.ui-widget-overlay').wrap('<div class="abc" />');
Where abc
is the name of your 'CSS wrapper' - see Stack Overflow question Custom CSS scope and jQuery UI dialog themes where I found the answer from Evgeni Nabokov. For more information on the CSS wrapper in use with a jQuery UI dialog box - see the following (but note they do NOT really solve the issue of the CSS wrapper with the dialog box - you need the above comments to help there, Using Multiple jQuery UI Themes on a Single Page (Filament blog).
Note that "number of cores" might not be a particularly useful number, you might have to qualify it a bit more. How do you want to count multi-threaded CPUs such as Intel HT, IBM Power5 and Power6, and most famously, Sun's Niagara/UltraSparc T1 and T2? Or even more interesting, the MIPS 1004k with its two levels of hardware threading (supervisor AND user-level)... Not to mention what happens when you move into hypervisor-supported systems where the hardware might have tens of CPUs but your particular OS only sees a few.
The best you can hope for is to tell the number of logical processing units that you have in your local OS partition. Forget about seeing the true machine unless you are a hypervisor. The only exception to this rule today is in x86 land, but the end of non-virtual machines is coming fast...
Use a normal javascript timer:
$(function(){
function show_popup(){
$("#message").slideUp();
};
window.setTimeout( show_popup, 5000 ); // 5 seconds
});
This will wait 5 seconds after the DOM is ready. If you want to wait until the page is actually loaded
you need to use this:
$(window).load(function(){
function show_popup(){
$("#message").slideUp();
};
window.setTimeout( show_popup, 5000 ); // 5 seconds
})
EDIT: In answer to the OP's comment asking if there is a way to do it in jQuery and not use setTimeout
the answer is no. But if you wanted to make it more "jQueryish" you could wrap it like this:
$.wait = function( callback, seconds){
return window.setTimeout( callback, seconds * 1000 );
}
You could then call it like this:
$.wait( function(){ $("#message").slideUp() }, 5);
Considering that this is the first stack overflow result when google searching this topic, it bears mentioning that prefixing u
to unicode strings is optional in Python 3. (Python 2 example was copied from the top answer)
Python 3 (both work):
print('\u0420\u043e\u0441\u0441\u0438\u044f')
print(u'\u0420\u043e\u0441\u0441\u0438\u044f')
Python 2:
print u'\u0420\u043e\u0441\u0441\u0438\u044f'
I linux this works too:
import sys
sys.path.extend(["/path/to/dotpy/file/"])
If you pass a String argument it will count the repetition of each word
/**
* @param string
* @return map which contain the word and value as the no of repatation
*/
public Map findDuplicateString(String str) {
String[] stringArrays = str.split(" ");
Map<String, Integer> map = new HashMap<String, Integer>();
Set<String> words = new HashSet<String>(Arrays.asList(stringArrays));
int count = 0;
for (String word : words) {
for (String temp : stringArrays) {
if (word.equals(temp)) {
++count;
}
}
map.put(word, count);
count = 0;
}
return map;
}
output:
Word1=2, word2=4, word2=1,. . .
In April 2017 a patch was merged into Safari, so it aligned with the other browsers. This was released with Safari 11.
A switch
statement can only be used for integral values, not for values of user-defined type. And even if it could, your input operation doesn't work, either.
You might want this:
#include <string>
#include <iostream>
std::string input;
if (!std::getline(std::cin, input)) { /* error, abort! */ }
if (input == "Option 1")
{
// ...
}
else if (input == "Option 2")
{
// ...
}
// etc.
check this quick reminder of file path
Here is all you need to know about relative file paths:
Minizip does have an example programs to demonstrate its usage - the files are called minizip.c and miniunz.c.
Update: I had a few minutes so I whipped up this quick, bare bones example for you. It's very smelly C, and I wouldn't use it without major improvements. Hopefully it's enough to get you going for now.
// uzip.c - Simple example of using the minizip API.
// Do not use this code as is! It is educational only, and probably
// riddled with errors and leaks!
#include <stdio.h>
#include <string.h>
#include "unzip.h"
#define dir_delimter '/'
#define MAX_FILENAME 512
#define READ_SIZE 8192
int main( int argc, char **argv )
{
if ( argc < 2 )
{
printf( "usage:\n%s {file to unzip}\n", argv[ 0 ] );
return -1;
}
// Open the zip file
unzFile *zipfile = unzOpen( argv[ 1 ] );
if ( zipfile == NULL )
{
printf( "%s: not found\n" );
return -1;
}
// Get info about the zip file
unz_global_info global_info;
if ( unzGetGlobalInfo( zipfile, &global_info ) != UNZ_OK )
{
printf( "could not read file global info\n" );
unzClose( zipfile );
return -1;
}
// Buffer to hold data read from the zip file.
char read_buffer[ READ_SIZE ];
// Loop to extract all files
uLong i;
for ( i = 0; i < global_info.number_entry; ++i )
{
// Get info about current file.
unz_file_info file_info;
char filename[ MAX_FILENAME ];
if ( unzGetCurrentFileInfo(
zipfile,
&file_info,
filename,
MAX_FILENAME,
NULL, 0, NULL, 0 ) != UNZ_OK )
{
printf( "could not read file info\n" );
unzClose( zipfile );
return -1;
}
// Check if this entry is a directory or file.
const size_t filename_length = strlen( filename );
if ( filename[ filename_length-1 ] == dir_delimter )
{
// Entry is a directory, so create it.
printf( "dir:%s\n", filename );
mkdir( filename );
}
else
{
// Entry is a file, so extract it.
printf( "file:%s\n", filename );
if ( unzOpenCurrentFile( zipfile ) != UNZ_OK )
{
printf( "could not open file\n" );
unzClose( zipfile );
return -1;
}
// Open a file to write out the data.
FILE *out = fopen( filename, "wb" );
if ( out == NULL )
{
printf( "could not open destination file\n" );
unzCloseCurrentFile( zipfile );
unzClose( zipfile );
return -1;
}
int error = UNZ_OK;
do
{
error = unzReadCurrentFile( zipfile, read_buffer, READ_SIZE );
if ( error < 0 )
{
printf( "error %d\n", error );
unzCloseCurrentFile( zipfile );
unzClose( zipfile );
return -1;
}
// Write data to file.
if ( error > 0 )
{
fwrite( read_buffer, error, 1, out ); // You should check return of fwrite...
}
} while ( error > 0 );
fclose( out );
}
unzCloseCurrentFile( zipfile );
// Go the the next entry listed in the zip file.
if ( ( i+1 ) < global_info.number_entry )
{
if ( unzGoToNextFile( zipfile ) != UNZ_OK )
{
printf( "cound not read next file\n" );
unzClose( zipfile );
return -1;
}
}
}
unzClose( zipfile );
return 0;
}
I built and tested it with MinGW/MSYS on Windows like this:
contrib/minizip/$ gcc -I../.. -o unzip uzip.c unzip.c ioapi.c ../../libz.a
contrib/minizip/$ ./unzip.exe /j/zlib-125.zip
Here is the C++ code:
bool FindSumZero(int a[], int n, int& x, int& y, int& z)
{
if (n < 3)
return false;
sort(a, a+n);
for (int i = 0; i < n-2; ++i)
{
int j = i+1;
int k = n-1;
while (k >= j)
{
int s = a[i]+a[j]+a[k];
if (s == 0 && i != j && j != k && k != i)
{
x = a[i], y = a[j], z = a[k];
return true;
}
if (s > 0)
--k;
else
++j;
}
}
return false;
}
No. Standard CSS does not provide the kind of thing you're looking for.
However, you might want to look into LESS and SASS.
These are two projects which aim to extend default CSS syntax by introducing additional features, including variables, nested rules, and other enhancements.
They allow you to write much more structured CSS code, and either of them will almost certainly solve your particular use case.
Of course, none of the browsers support their extended syntax (especially since the two projects each have different syntax and features), but what they do is provide a "compiler" which converts your LESS or SASS code into standard CSS, which you can then deploy on your site.
I modified the accepted answer and now it can get the command including primary key and foreign key in a certain schema.
declare @table varchar(100)
declare @schema varchar(100)
set @table = 'Persons' -- set table name here
set @schema = 'OT' -- set SCHEMA name here
declare @sql table(s varchar(1000), id int identity)
-- create statement
insert into @sql(s) values ('create table ' + @table + ' (')
-- column list
insert into @sql(s)
select
' '+column_name+' ' +
data_type + coalesce('('+cast(character_maximum_length as varchar)+')','') + ' ' +
case when exists (
select id from syscolumns
where object_name(id)=@table
and name=column_name
and columnproperty(id,name,'IsIdentity') = 1
) then
'IDENTITY(' +
cast(ident_seed(@table) as varchar) + ',' +
cast(ident_incr(@table) as varchar) + ')'
else ''
end + ' ' +
( case when IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' +
coalesce('DEFAULT '+COLUMN_DEFAULT,'') + ','
from information_schema.columns where table_name = @table and table_schema = @schema
order by ordinal_position
-- primary key
declare @pkname varchar(100)
select @pkname = constraint_name from information_schema.table_constraints
where table_name = @table and constraint_type='PRIMARY KEY'
if ( @pkname is not null ) begin
insert into @sql(s) values(' PRIMARY KEY (')
insert into @sql(s)
select ' '+COLUMN_NAME+',' from information_schema.key_column_usage
where constraint_name = @pkname
order by ordinal_position
-- remove trailing comma
update @sql set s=left(s,len(s)-1) where id=@@identity
insert into @sql(s) values (' )')
end
else begin
-- remove trailing comma
update @sql set s=left(s,len(s)-1) where id=@@identity
end
-- foreign key
declare @fkname varchar(100)
select @fkname = constraint_name from information_schema.table_constraints
where table_name = @table and constraint_type='FOREIGN KEY'
if ( @fkname is not null ) begin
insert into @sql(s) values(',')
insert into @sql(s) values(' FOREIGN KEY (')
insert into @sql(s)
select ' '+COLUMN_NAME+',' from information_schema.key_column_usage
where constraint_name = @fkname
order by ordinal_position
-- remove trailing comma
update @sql set s=left(s,len(s)-1) where id=@@identity
insert into @sql(s) values (' ) REFERENCES ')
insert into @sql(s)
SELECT
OBJECT_NAME(fk.referenced_object_id)
FROM
sys.foreign_keys fk
INNER JOIN
sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
INNER JOIN
sys.columns c1 ON fkc.parent_column_id = c1.column_id AND fkc.parent_object_id = c1.object_id
INNER JOIN
sys.columns c2 ON fkc.referenced_column_id = c2.column_id AND fkc.referenced_object_id = c2.object_id
where fk.name = @fkname
insert into @sql(s)
SELECT
'('+c2.name+')'
FROM
sys.foreign_keys fk
INNER JOIN
sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
INNER JOIN
sys.columns c1 ON fkc.parent_column_id = c1.column_id AND fkc.parent_object_id = c1.object_id
INNER JOIN
sys.columns c2 ON fkc.referenced_column_id = c2.column_id AND fkc.referenced_object_id = c2.object_id
where fk.name = @fkname
end
-- closing bracket
insert into @sql(s) values( ')' )
-- result!
select s from @sql order by id
The main
method is the entry point of a Java application.
Specifically?when the Java Virtual Machine is told to run an application by specifying its class (by using the java
application launcher), it will look for the main
method with the signature of public static void main(String[])
.
From Sun's java
command page:
The java tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's main method.
The method must be declared public and static, it must not return any value, and it must accept a
String
array as a parameter. The method declaration must look like the following:public static void main(String args[])
For additional resources on how an Java application is executed, please refer to the following sources:
The run
method is the entry point for a new Thread
or an class implementing the Runnable
interface. It is not called by the Java Virutal Machine when it is started up by the java
command.
As a Thread
or Runnable
itself cannot be run directly by the Java Virtual Machine, so it must be invoked by the Thread.start()
method. This can be accomplished by instantiating a Thread
and calling its start
method in the main
method of the application:
public class MyRunnable implements Runnable
{
public void run()
{
System.out.println("Hello World!");
}
public static void main(String[] args)
{
new Thread(new MyRunnable()).start();
}
}
For more information and an example of how to start a subclass of Thread
or a class implementing Runnable
, see Defining and Starting a Thread from the Java Tutorials.
The init
method is the first method called in an Applet or JApplet.
When an applet is loaded by the Java plugin of a browser or by an applet viewer, it will first call the Applet.init
method. Any initializations that are required to use the applet should be executed here. After the init
method is complete, the start
method is called.
For more information about when the init
method of an applet is called, please read about the lifecycle of an applet at The Life Cycle of an Applet from the Java Tutorials.
See also: How to Make Applets from the Java Tutorial.
Following query also can be used:
select *
from t23
where trunc(start_date) between trunc(to_date('01/15/2010','mm/dd/yyyy')) and trunc(to_date('01/17/2010','mm/dd/yyyy'))
You can also go through following:
Example:
my_list=[1,2,3,4,5,"abc","def"]
with open('your_file.txt', 'w') as file:
for item in my_list:
file.write("%s\n" % item)
Output:
In your_file.txt
items are saved like:
1
2
3
4
5
abc
def
Your script also saves as above.
Otherwise, you can use pickle
import pickle
my_list=[1,2,3,4,5,"abc","def"]
#to write
with open('your_file.txt', 'wb') as file:
pickle.dump(my_list, file)
#to read
with open ('your_file.txt', 'rb') as file:
Outlist = pickle.load(file)
print(Outlist)
Output: [1, 2, 3, 4, 5, 'abc', 'def']
It save dump the list same as a list when we load it we able to read.
Also by simplejson
possible same as above output
import simplejson as sj
my_list=[1,2,3,4,5,"abc","def"]
#To write
with open('your_file.txt', 'w') as file:
sj.dump(my_list, file)
#To save
with open('your_file.txt', 'r') as file:
mlist=sj.load(file)
print(mlist)
In my case the reason was some wrong certificate that could not be loaded. I found out about it from the Event Viewer, under System:
A fatal error occurred when attempting to access the TLS server credential private key. The error code returned from the cryptographic module is 0x8009030D. The internal error state is 10001.
db:create
- Creates the database for the current RAILS_ENV environment. If RAILS_ENV is not specified it defaults to the development and test databases.
db:create:all
- Creates the database for all environments.
db:drop
- Drops the database for the current RAILS_ENV environment. If RAILS_ENV is not specified it defaults to the development and test databases.
db:drop:all
- Drops the database for all environments.
db:migrate
- Runs migrations for the current environment that have not run yet. By default it will run migrations only in the development environment.
db:migrate:redo
- Runs db:migrate:down and db:migrate:up or db:migrate:rollback and db:migrate:up depending on the specified migration.
db:migrate:up
- Runs the up for the given migration VERSION.
db:migrate:down
- Runs the down for the given migration VERSION.
db:migrate:status
- Displays the current migration status.
db:migrate:rollback
- Rolls back the last migration.
db:version
- Prints the current schema version.
db:forward
- Pushes the schema to the next version.
db:seed
- Runs the db/seeds.rb file.
db:schema:load
Recreates the database from the schema.rb file. Deletes existing data.
db:schema:dump
Dumps the current environment’s schema to db/schema.rb.
db:structure:load
- Recreates the database from the structure.sql file.
db:structure:dump
- Dumps the current environment’s schema to db/structure.sql.
(You can specify another file with SCHEMA=db/my_structure.sql
)
db:setup
Runs db:create, db:schema:load and db:seed.
db:reset
Runs db:drop and db:setup.
db:migrate:reset
- Runs db:drop, db:create and db:migrate.
db:test:prepare
- Check for pending migrations and load the test schema. (If you run rake without any arguments it will do this by default.)
db:test:clone
- Recreate the test database from the current environment’s database schema.
db:test:clone_structure
- Similar to db:test:clone, but it will ensure that your test database has the same structure, including charsets and collations, as your current environment’s database.
db:environment:set
- Set the current RAILS_ENV environment in the ar_internal_metadata table. (Used as part of the protected environment check.)
db:check_protected_environments
- Checks if a destructive action can be performed in the current RAILS_ENV environment. Used internally when running a destructive action such as db:drop or db:schema:load.
You can solve it by using the useRef
hook but then it's will not re-render when it' updated. I have created a hooks called useStateRef, that give you the good from both worlds. It's like a state that when it's updated the Component re-render, and it's like a "ref" that always have the latest value.
See this example:
var [state,setState,ref]=useStateRef(0)
It works exactly like useState
but in addition, it gives you the current state under ref.current
Learn more:
I've always found you need both
android:screenOrientation="nosensor" android:configChanges="keyboardHidden|orientation"
For Jpa based application: base package scan
@EnableJpaRepositories(basePackages = "repository")
You can try it once!!!
Project Structure
com
+- stack
+- app
| +- Application.java
+- controller
| +- EmployeeController.java
+- service
| +- EmployeeService.java
+- repository
| +- EmployeeRepository.java
+- model
| +- Employee.java
-pom.xml
dependencies:
mysql, lombok, data-jpa
application.properties
#Data source :
spring.datasource.url=jdbc:mysql://localhost:3306/employee?useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.generate-ddl=true
spring.datasource.driverClassName=com.mysql.jdbc.Driver
#Jpa/Hibernate :
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto = update
Employee.java
@Entity
@Table (name = "employee")
@Getter
@Setter
public class Employee {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
private Long id;
@Column (name = "first_name")
private String firstName;
@Column (name = "last_name")
private String lastName;
@Column (name = "email")
private String email;
@Column (name = "phone_number")
private String phoneNumber;
@Column (name = "emp_desg")
private String desgination;
}
EmployeeRepository.java
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
EmployeeController.java
@RestController
public class EmployeeController {
@Autowired
private EmployeeService empService;
@GetMapping (value = "/employees")
public List<Employee> getAllEmployee(){
return empService.getAllEmployees();
}
@PostMapping (value = "/employee")
public ResponseEntity<Employee> addEmp(@RequestBody Employee emp, HttpServletRequest
request) throws URISyntaxException {
HttpHeaders headers = new HttpHeaders();
headers.setLocation(new URI(request.getRequestURI() + "/" + emp.getId()));
empService.saveEmployee(emp);
return new ResponseEntity<Employee>(emp, headers, HttpStatus.CREATED);
}
EmployeeService.java
public interface EmployeeService {
public List<Employee> getAllEmployees();
public Employee saveEmployee(Employee emp);
}
EmployeeServiceImpl.java
@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeRepository empRepository;
@Override
public List<Employee> getAllEmployees() {
return empRepository.findAll();
}
@Override
public Employee saveEmployee(Employee emp) {
return empRepository.save(emp);
}
}
EmployeeApplication.java
@SpringBootApplication
@EnableJpaRepositories(basePackages = "repository")
public class EmployeeApplication {
public static void main(String[] args) {
SpringApplication.run(EmployeeApplication.class, args);
}
}
Declaring a PRIMARY KEY
or UNIQUE
constraint causes SQL Server to automatically create an index.
An unique index can be created without matching a constraint, but a constraint (either primary key or unique) cannot exist without having a unique index.
From here, the creation of a constraint will:
and at the same time dropping the constraint will drop the associated index.
So, is there actual difference between a PRIMARY KEY
or UNIQUE INDEX
:
NULL
values are not allowed in PRIMARY KEY
, but allowed in UNIQUE
index; and like in set operators (UNION, EXCEPT, INTERSECT), here NULL = NULL
which means that you can have only one value as two NULL
s are find as duplicates of each other;PRIMARY KEY
may exists per table while 999 unique indexes can be createdPRIMARY KEY
constraint is created, it is created as clustered unless there is already a clustered index on the table or NONCLUSTERED
is used in its definition; when UNIQUE
index is created, it is created as NONCLUSTERED
unless it is not specific to be CLUSTERED
and such already does not exist;To convert the byte[] to string[], simply use the below line.
byte[] fileData; // Some byte array
//Convert byte[] to string[]
var table = (Encoding.Default.GetString(
fileData,
0,
fileData.Length - 1)).Split(new string[] { "\r\n", "\r", "\n" },
StringSplitOptions.None);
I was interested in this as well and came across some examples on the Spring Boot site.
// get with query string parameters e.g. /system/resource?id="rtze1cd2"&person="sam smith"
// so below the first query parameter id is the variable and name is the variable
// id is shown below as a RequestParam
@GetMapping("/system/resource")
// this is for swagger docs
@ApiOperation(value = "Get the resource identified by id and person")
ResponseEntity<?> getSomeResourceWithParameters(@RequestParam String id, @RequestParam("person") String name) {
InterestingResource resource = getMyInterestingResourc(id, name);
logger.info("Request to get an id of "+id+" with a name of person: "+name);
return new ResponseEntity<Object>(resource, HttpStatus.OK);
}
I run into the same problem and wrote a little shared-memory utility class to work around it.
I'm using multiprocessing.RawArray
(lockfree), and also the access to the arrays is not synchronized at all (lockfree), be careful not to shoot your own feet.
With the solution I get speedups by a factor of approx 3 on a quad-core i7.
Here's the code: Feel free to use and improve it, and please report back any bugs.
'''
Created on 14.05.2013
@author: martin
'''
import multiprocessing
import ctypes
import numpy as np
class SharedNumpyMemManagerError(Exception):
pass
'''
Singleton Pattern
'''
class SharedNumpyMemManager:
_initSize = 1024
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(SharedNumpyMemManager, cls).__new__(
cls, *args, **kwargs)
return cls._instance
def __init__(self):
self.lock = multiprocessing.Lock()
self.cur = 0
self.cnt = 0
self.shared_arrays = [None] * SharedNumpyMemManager._initSize
def __createArray(self, dimensions, ctype=ctypes.c_double):
self.lock.acquire()
# double size if necessary
if (self.cnt >= len(self.shared_arrays)):
self.shared_arrays = self.shared_arrays + [None] * len(self.shared_arrays)
# next handle
self.__getNextFreeHdl()
# create array in shared memory segment
shared_array_base = multiprocessing.RawArray(ctype, np.prod(dimensions))
# convert to numpy array vie ctypeslib
self.shared_arrays[self.cur] = np.ctypeslib.as_array(shared_array_base)
# do a reshape for correct dimensions
# Returns a masked array containing the same data, but with a new shape.
# The result is a view on the original array
self.shared_arrays[self.cur] = self.shared_arrays[self.cnt].reshape(dimensions)
# update cnt
self.cnt += 1
self.lock.release()
# return handle to the shared memory numpy array
return self.cur
def __getNextFreeHdl(self):
orgCur = self.cur
while self.shared_arrays[self.cur] is not None:
self.cur = (self.cur + 1) % len(self.shared_arrays)
if orgCur == self.cur:
raise SharedNumpyMemManagerError('Max Number of Shared Numpy Arrays Exceeded!')
def __freeArray(self, hdl):
self.lock.acquire()
# set reference to None
if self.shared_arrays[hdl] is not None: # consider multiple calls to free
self.shared_arrays[hdl] = None
self.cnt -= 1
self.lock.release()
def __getArray(self, i):
return self.shared_arrays[i]
@staticmethod
def getInstance():
if not SharedNumpyMemManager._instance:
SharedNumpyMemManager._instance = SharedNumpyMemManager()
return SharedNumpyMemManager._instance
@staticmethod
def createArray(*args, **kwargs):
return SharedNumpyMemManager.getInstance().__createArray(*args, **kwargs)
@staticmethod
def getArray(*args, **kwargs):
return SharedNumpyMemManager.getInstance().__getArray(*args, **kwargs)
@staticmethod
def freeArray(*args, **kwargs):
return SharedNumpyMemManager.getInstance().__freeArray(*args, **kwargs)
# Init Singleton on module load
SharedNumpyMemManager.getInstance()
if __name__ == '__main__':
import timeit
N_PROC = 8
INNER_LOOP = 10000
N = 1000
def propagate(t):
i, shm_hdl, evidence = t
a = SharedNumpyMemManager.getArray(shm_hdl)
for j in range(INNER_LOOP):
a[i] = i
class Parallel_Dummy_PF:
def __init__(self, N):
self.N = N
self.arrayHdl = SharedNumpyMemManager.createArray(self.N, ctype=ctypes.c_double)
self.pool = multiprocessing.Pool(processes=N_PROC)
def update_par(self, evidence):
self.pool.map(propagate, zip(range(self.N), [self.arrayHdl] * self.N, [evidence] * self.N))
def update_seq(self, evidence):
for i in range(self.N):
propagate((i, self.arrayHdl, evidence))
def getArray(self):
return SharedNumpyMemManager.getArray(self.arrayHdl)
def parallelExec():
pf = Parallel_Dummy_PF(N)
print(pf.getArray())
pf.update_par(5)
print(pf.getArray())
def sequentialExec():
pf = Parallel_Dummy_PF(N)
print(pf.getArray())
pf.update_seq(5)
print(pf.getArray())
t1 = timeit.Timer("sequentialExec()", "from __main__ import sequentialExec")
t2 = timeit.Timer("parallelExec()", "from __main__ import parallelExec")
print("Sequential: ", t1.timeit(number=1))
print("Parallel: ", t2.timeit(number=1))
var json = {"ListID" : "1", "ItemName":"test"};
$.ajax({
url: url,
type: 'POST',
data: username,
cache:false,
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success:function(response){
console.log("Success")
},
error : function(xhr, status, error) {
console.log("error")
}
);
Sorry for awakening an old question like this. But I think what the original author wanted as an answer was:
You need to force your program to make the graphic update after you make the change to the textbox1. You can do that by invoking Update();
textBox1.Text += "\r\nThread Sleeps!";
textBox1.Update();
System.Threading.Thread.Sleep(4000);
textBox1.Text += "\r\nThread awakens!";
textBox1.Update();
Normally this will be done automatically when the thread is done.
Ex, you press a button, changes are made to the text, thread dies, and then .Update()
is fired and you see the changes.
(I'm not an expert so I cant really tell you when its fired, but its something similar to this any way.)
In this case, you make a change, pause the thread, and then change the text again, and when the thread finally dies the .Update()
is fired. This resulting in you only seeing the last change made to the text.
You would experience the same issue if you had a long execution between the text changes.
you could probably use the gzip -t option to test the files integrity
http://linux.about.com/od/commands/l/blcmdl1_gzip.htm
To test the gzip file is not corrupt:
gunzip -t file.tar.gz
To test the tar file inside is not corrupt:
gunzip -c file.tar.gz | tar -t > /dev/null
As part of the backup you could probably just run the latter command and check the value of $? afterwards for a 0 (success) value. If either the tar or the gzip has an issue, $? will have a non zero value.
There is a section in the MySQL manual on how to reset the root password which will solve your problem.
Add GSM Modem Support while creating AVD in your virtual devices from Android SDK and AVD Manager...
Did you try InputMethodManager.SHOW_IMPLICIT
in first window.
and for hiding in second window use InputMethodManager.HIDE_IMPLICIT_ONLY
EDIT :
If its still not working then probably you are putting it at the wrong place. Override onFinishInflate()
and show/hide there.
@override
public void onFinishInflate() {
/* code to show keyboard on startup */
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mUserNameEdit, InputMethodManager.SHOW_IMPLICIT);
}
Sadly, Java 8 did not introduce pairs or tuples. You can always use org.apache.commons.lang3.tuple of course (which personally I do use in combination with Java 8) or you can create your own wrappers. Or use Maps. Or stuff like that, as is explained in the accepted answer to that question you linked to.
UPDATE: JDK 14 is introducing records as a preview feature. These aren't tuples, but can be used to save many of the same problems. In your specific example from above, that could look something like this:
public class Jdk14Example {
record CountForIndex(int index, long count) {}
public static void main(String[] args) {
boolean [][] directed_acyclic_graph = new boolean[][]{
{false, true, false, true, false, true},
{false, false, false, true, false, true},
{false, false, false, true, false, true},
{false, false, false, false, false, true},
{false, false, false, false, false, true},
{false, false, false, false, false, false}
};
System.out.println(
IntStream.range(0, directed_acyclic_graph.length)
.parallel()
.mapToObj(i -> {
long count = IntStream.range(0, directed_acyclic_graph[i].length)
.filter(j -> directed_acyclic_graph[j][i])
.count();
return new CountForIndex(i, count);
}
)
.filter(n -> n.count == 0)
.collect(() -> new ArrayList<CountForIndex>(), (c, e) -> c.add(e), (c1, c2) -> c1.addAll(c2))
);
}
}
When compiled and run with JDK 14 (at the time of writing, this an early access build) using the --enable-preview
flag, you get the following result:
[CountForIndex[index=0, count=0], CountForIndex[index=2, count=0], CountForIndex[index=4, count=0]]
With new features of ES6 block level scoping is managed:
var funcs = [];
for (let i = 0; i < 3; i++) { // let's create 3 functions
funcs[i] = function() { // and store them in funcs
console.log("My value: " + i); // each should log its value.
};
}
for (let j = 0; j < 3; j++) {
funcs[j](); // and now let's run each one to see
}
The code in OP's question is replaced with let
instead of var
.
DOMDocument is a great choice. It's a module specifically designed for creating and manipulating XML documents. You can create a document from scratch, or open existing documents (or strings) and navigate and modify their structures.
$xml = new DOMDocument();
$xml_album = $xml->createElement("Album");
$xml_track = $xml->createElement("Track");
$xml_album->appendChild( $xml_track );
$xml->appendChild( $xml_album );
$xml->save("/tmp/test.xml");
To re-open and write:
$xml = new DOMDocument();
$xml->load('/tmp/test.xml');
$nodes = $xml->getElementsByTagName('Album') ;
if ($nodes->length > 0) {
//insert some stuff using appendChild()
}
//re-save
$xml->save("/tmp/test.xml");
You should read the angular element docs if you haven't yet, so you can understand what is supported by jqLite and what not -jqlite is a subset of jquery built into angular.
Those selectors won't work with jqLite alone, since selectors by id are not supported.
var target = angular.element('#appBusyIndicator');
var target = angular.element('appBusyIndicator');
So, either :
Edit: Note that jQuery should be loaded before angularJS in order to take precedence over jqLite:
Real jQuery always takes precedence over jqLite, provided it was loaded before DOMContentLoaded event fired.
Edit2: I missed the second part of the question before:
The issue with <input type="number">
, I think it is not an angular issue, it is the intended behaviour of the native html5 number element.
It won't return a non-numeric value even if you try to retrieve it with jquery's .val()
or with the raw .value
attribute.
I think it is dangerous to use $.isEmptyObject from jquery to check whether the array is empty, as @jesenko mentioned. I just met that problem.
In the isEmptyObject doc, it mentions:
The argument should always be a plain JavaScript Object
which you can determine by $.isPlainObject
. The return of $.isPlainObject([])
is false.
2A. As far as last seven days have much less rows than whole table an index can help
2B. If you are interested only in Created_Date you can try using some group by and count, it should help with the result set size
you will need to use a PHP script (or an other server side language for this)
<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile('original.pdf');
?>
and use httacces to redirect (rewrite) to the PHP file instead of the pdf
In case you need the answer to be a member of the input numpy array:
Just to add that the percentile function in numpy by default calculates the output as a linear weighted average of the two neighboring entries in the input vector. In some cases people may want the returned percentile to be an actual element of the vector, in this case, from v1.9.0 onwards you can use the "interpolation" option, with either "lower", "higher" or "nearest".
import numpy as np
x=np.random.uniform(10,size=(1000))-5.0
np.percentile(x,70) # 70th percentile
2.075966046220879
np.percentile(x,70,interpolation="nearest")
2.0729677997904314
The latter is an actual entry in the vector, while the former is a linear interpolation of two vector entries that border the percentile
add a condition to check for the admin directory, something like:
RewriteCond %{REQUEST_URI} !^/?(admin|user)/
RewriteRule ^([^/] )/([^/] )\.html$ index.php?lang=$1&mod=$2 [L]
RewriteCond %{REQUEST_URI} !^/?(admin|user)/
RewriteRule ^([^/] )/$ index.php?lang=$1&mod=home [L]
I'm starting to learn how to code with Swift and was trying to solve this too, this is what I came up with on Swift's playground:
// Code
var x = 1
var y = 2
var lowX = 1
var lowY = 1
var highX = 3
var highY = 3
if (x, y) >= (lowX, lowY) && (x, y) <= (highX, highY ) {
print("inside")
} else {
print("not inside")
}
It prints inside
For those who want an elegant, bash version-independent solution (in fact should work in other modern shells) and those who love to use one-liners for quick tasks. Here we go!
ls | grep . && echo 'files found' || echo 'files not found'
(note as one of the comments mentioned, ls -al
and in fact, just -l
and -a
will all return something, so in my answer I use simple ls
The reference to 480px has been removed. Instead it says:
/* Extra small devices (phones, less than 768px) */
/* No media query since this is the default in Bootstrap */
There isn't a breakpoint below 768px in Bootstrap 3.
If you want to use the @screen-sm-min
and other mixins then you need to be compiling with LESS, see http://getbootstrap.com/css/#grid-less
Here's a tutorial on how to use Bootstrap 3 and LESS: http://www.helloerik.com/bootstrap-3-less-workflow-tutorial
'\r' = carriage return and '\n' = line feed.
In fact, there are some different behaviors when you use them in different OSes. On Unix it is '\n', but it is '\r''\n' on Windows.
After reading all comments. this was my resolution:
I had to "Add" it again than commit:
$ git commit -i -m support.html "doit once for all" [master 18ea92e] support.html
You simply can't.
Code inspectors are designed for debugging HTML and Javascript. They do so by showing the live DOM object of the web page. That means it reveals HTML code of everything you see on the page, even if they're generated by Javascript. Some inspectors even shows the code inside iframes.
There are some javascript tricks to disable some keyboard, mouse interaction on the page. But there always are work around to those tricks. For instance, you can use the browser top menu to enable DOM inspector without a problem.
Try theses:
They are outside the control of Javascripts.
Think about this:
Basically, browsers are god to your Javascript. And they want to grant the web developer super power with code inspectors. Even if your trick works for a while, the browsers would want to undo it in the future.
You're waging war against god and you're doomed to fail.
To put it simple, if you do not want people to get something in their browser, you should never send it to their browser in the first place.
This is what worked for me.
<!DOCTYPE html>
<form action="desired Link">
<button> <img src="desired image URL"/>
</button>
</form>
<style>
</style>
You can use the below query to identify the values. But please keep in mind that this will not give you the results from encrypted stored procedure.
SELECT DISTINCT OBJECT_NAME(comments.id) OBJECT_NAME
,objects.type_desc
FROM syscomments comments
,sys.objects objects
WHERE comments.id = objects.object_id
AND TEXT LIKE '%CreatedDate%'
ORDER BY 1
Python
if x is not None
orif not x is None
?
TLDR: The bytecode compiler parses them both to x is not None
- so for readability's sake, use if x is not None
.
We use Python because we value things like human readability, useability, and correctness of various paradigms of programming over performance.
Python optimizes for readability, especially in this context.
The not
binds more weakly than is
, so there is no logical difference here. See the documentation:
The operators
is
andis not
test for object identity:x is y
is true if and only if x and y are the same object.x is not y
yields the inverse truth value.
The is not
is specifically provided for in the Python grammar as a readability improvement for the language:
comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
And so it is a unitary element of the grammar as well.
Of course, it is not parsed the same:
>>> import ast
>>> ast.dump(ast.parse('x is not None').body[0].value)
"Compare(left=Name(id='x', ctx=Load()), ops=[IsNot()], comparators=[Name(id='None', ctx=Load())])"
>>> ast.dump(ast.parse('not x is None').body[0].value)
"UnaryOp(op=Not(), operand=Compare(left=Name(id='x', ctx=Load()), ops=[Is()], comparators=[Name(id='None', ctx=Load())]))"
But then the byte compiler will actually translate the not ... is
to is not
:
>>> import dis
>>> dis.dis(lambda x, y: x is not y)
1 0 LOAD_FAST 0 (x)
3 LOAD_FAST 1 (y)
6 COMPARE_OP 9 (is not)
9 RETURN_VALUE
>>> dis.dis(lambda x, y: not x is y)
1 0 LOAD_FAST 0 (x)
3 LOAD_FAST 1 (y)
6 COMPARE_OP 9 (is not)
9 RETURN_VALUE
So for the sake of readability and using the language as it was intended, please use is not
.
To not use it is not wise.
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<title>Bootstrap Example</title>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<style>_x000D_
input[type="radio"] {_x000D_
-ms-transform: scale(1.5); /* IE 9 */_x000D_
-webkit-transform: scale(1.5); /* Chrome, Safari, Opera */_x000D_
transform: scale(1.5);_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
<h2>Form control: inline radio buttons</h2>_x000D_
<p>The form below contains three inline radio buttons:</p>_x000D_
<form>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="optradio">Option 1_x000D_
</label>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="optradio">Option 2_x000D_
</label>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="optradio">Option 3_x000D_
</label>_x000D_
</form>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_