The String#replaceAll()
interprets the argument as a regular expression. The \
is an escape character in both String
and regex
. You need to double-escape it for regex:
string.replaceAll("\\\\", "\\\\\\\\");
But you don't necessarily need regex for this, simply because you want an exact character-by-character replacement and you don't need patterns here. So String#replace()
should suffice:
string.replace("\\", "\\\\");
Update: as per the comments, you appear to want to use the string in JavaScript context. You'd perhaps better use StringEscapeUtils#escapeEcmaScript()
instead to cover more characters.
A simple way is to use python. in python terminal type
r"C:\Users\surfcat\Desktop\2006_dissimilarity.csv" and you'll get back 'C:\Users\surfcat\Desktop\2006_dissimilarity.csv'
No need to use str.replace
or string.replace
here, just convert that string to a raw string:
>>> strs = r"C:\Users\Josh\Desktop\20130216"
^
|
notice the 'r'
Below is the repr
version of the above string, that's why you're seeing \\
here.
But, in fact the actual string contains just '\'
not \\
.
>>> strs
'C:\\Users\\Josh\\Desktop\\20130216'
>>> s = r"f\o"
>>> s #repr representation
'f\\o'
>>> len(s) #length is 3, as there's only one `'\'`
3
But when you're going to print this string you'll not get '\\'
in the output.
>>> print strs
C:\Users\Josh\Desktop\20130216
If you want the string to show '\\'
during print
then use str.replace
:
>>> new_strs = strs.replace('\\','\\\\')
>>> print new_strs
C:\\Users\\Josh\\Desktop\\20130216
repr
version will now show \\\\
:
>>> new_strs
'C:\\\\Users\\\\Josh\\\\Desktop\\\\20130216'
Slightly hacky, but it works:
const input = '\text';_x000D_
const output = JSON.stringify(input).replace(/((^")|("$))/g, "").trim();_x000D_
_x000D_
console.log({ input, output });_x000D_
// { input: '\text', output: '\\text' }
_x000D_
You can also try this for the double quotes:
JSON.stringify(sDemoString).slice(1, -1);
JSON.stringify('my string with "quotes"').slice(1, -1);
A hacky way of printing a backslash that doesn't involve escaping is to pass its character code to chr
:
>>> print(chr(92))
\
You can simply do a replace in your string like
Str.Replace(@"\\",@"\");
As HungryDB said the easier way for do that is:
$mystring = json_encode($my_json,JSON_UNESCAPED_SLASHES);
Have a look at your php version because this parameter has been added in version 5.4.0
I have used
str.replace("'", "");
to replace the single quote in my string. Its working fine for me.
var myNewString = myOldString.replace(/'/g, "\\'");
Go to File->Import Settings... and select the jar settings file
Update as of IntelliJ 2020:
Go to File -> Manage IDE Settings -> Import Settings...
here is solution, i create a text field to dynamic add new items in array my html code is
<input type="text" id="name">_x000D_
<input type="button" id="btn" value="Button">_x000D_
<div id="names">_x000D_
</div>
_x000D_
now type any thing in text field and click on button this will add item onto array and call function dispaly_arry
$(document).ready(function()_x000D_
{ _x000D_
function display_array()_x000D_
{_x000D_
$("#names").text('');_x000D_
$.each(names,function(index,value)_x000D_
{_x000D_
$('#names').append(value + '<br/>');_x000D_
});_x000D_
}_x000D_
_x000D_
var names = ['Alex','Billi','Dale'];_x000D_
display_array();_x000D_
$('#btn').click(function()_x000D_
{_x000D_
var name = $('#name').val();_x000D_
names.push(name);// appending value to arry _x000D_
display_array();_x000D_
_x000D_
});_x000D_
_x000D_
});_x000D_
_x000D_
showing array elements into div , you can use span but for this solution use same id .!
It’s quite common to define navigational properties in a model to be virtual. When a navigation property is defined as virtual, it can take advantage of certain Entity Framework functionality. The most common one is lazy loading.
Lazy loading is a nice feature of many ORMs because it allows you to dynamically access related data from a model. It will not unnecessarily fetch the related data until it is actually accessed, thus reducing the up-front querying of data from the database.
From book "ASP.NET MVC 5 with Bootstrap and Knockout.js"
Just for the sake of diversity, you can also do this if your array is not an array of numbers, but rather an array of objects that have properties that are numbers (e.g. amount):
array.inject(0){|sum,x| sum + x.amount}
when I give without http/http prefix in the proxy settings npm failed even when the proxy host and port were right values. It worked only after adding the protocol prefix.
I had to do it too. I found the solution from "Chris R" really good, but thought it could be more compatible in not adding any references. Chris, you talked about using Collection. So here is another solution using Collection. And it's not that slow, in my case. Also, with this solution, in adding the event "_SelectionChange", it's always working (no need of workbook_open).
Dim OldValues As New Collection
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'Copy old values
Set OldValues = Nothing
Dim c As Range
For Each c In Target
OldValues.Add c.Value, c.Address
Next c
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
On Local Error Resume Next ' To avoid error if the old value of the cell address you're looking for has not been copied
Dim c As Range
For Each c In Target
Debug.Print "New value of " & c.Address & " is " & c.Value & "; old value was " & OldValues(c.Address)
Next c
'Copy old values (in case you made any changes in previous lines of code)
Set OldValues = Nothing
For Each c In Target
OldValues.Add c.Value, c.Address
Next c
End Sub
Also check if the resource-name contains any illegal characters (for me it was a "-" in my-image)
I was trying to make my Angular app scroll to an anchor opon loading and ran into the URL rewriting rules of $routeProvider.
After long experimentation I settled on this:
angular.module("bla",[]).}])_x000D_
.run(function($location, $anchorScroll){_x000D_
$(document).ready(function() {_x000D_
if(location.hash && location.hash.length>=1) {_x000D_
var path = location.hash;_x000D_
var potentialAnchor = path.substring(path.lastIndexOf("/")+1);_x000D_
if ($("#" + potentialAnchor).length > 0) { // make sure this hashtag exists in the doc. _x000D_
location.hash = potentialAnchor;_x000D_
$anchorScroll();_x000D_
}_x000D_
} _x000D_
});
_x000D_
Assuming a
is a string. The Slice notation in python has the syntax -
list[<start>:<stop>:<step>]
So, when you do a[::-1]
, it starts from the end towards the first taking each element. So it reverses a. This is applicable for lists/tuples as well.
Example -
>>> a = '1234'
>>> a[::-1]
'4321'
Then you convert it to int and then back to string (Though not sure why you do that) , that just gives you back the string.
I use the Eclipse version called Mars which works with Java 7.
Go to Preferences -> Java -> Code Style -> Formatter
Click on the Edit Button shown in the right side of "Active Profile" drop down
Tabs: "Line wrapping"
Field: "Maximum line width", Set the desired value (Default value set to 120) to increase/decrease the line length in the editor
Note: Remember to rename the Active profile to the name of your choice, as the default Eclipse profile won't accept your changes.
You can get raw data using below method. BTW, this pattern is for Java 6. If you are using Java 7 or newer, please consider try-with-resources pattern.
public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
And then you can use returned string with Google Gson to map JSON to object of specified class, like this:
String data = getJSON("http://localhost/authmanager.php");
AuthMsg msg = new Gson().fromJson(data, AuthMsg.class);
System.out.println(msg);
There is a sample of AuthMsg class:
public class AuthMsg {
private int code;
private String message;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
JSON returned by http://localhost/authmanager.php must look like this:
{"code":1,"message":"Logged in"}
Regards
Java String
s aren't character Iterable
. You'll need:
for (int i = 0; i < examplestring.length(); i++) {
char c = examplestring.charAt(i);
...
}
Awkward I know.
You may use an iterator over each byte in the output of the subprocess. This allows inline update (lines ending with '\r' overwrite previous output line) from the subprocess:
from subprocess import PIPE, Popen
command = ["my_command", "-my_arg"]
# Open pipe to subprocess
subprocess = Popen(command, stdout=PIPE, stderr=PIPE)
# read each byte of subprocess
while subprocess.poll() is None:
for c in iter(lambda: subprocess.stdout.read(1) if subprocess.poll() is None else {}, b''):
c = c.decode('ascii')
sys.stdout.write(c)
sys.stdout.flush()
if subprocess.returncode != 0:
raise Exception("The subprocess did not terminate correctly.")
Using python 64 bit solves lot of problems.
Struggled to find this as well.
Heres a screenshot of how to do it:
Quickest (drops and creates all tables including data):
./manage.py reset appname | ./manage.py dbshell
Caution:
The following is the correct overload (in your example you are missing a closing }
to the routeValues
anonymous object so your code will throw an exception):
<a href="<%: Url.Action("GetByList", "Listing", new { name = "John", contact = "calgary, vancouver" }) %>">
<span>People</span>
</a>
Assuming you are using the default routes this should generate the following markup:
<a href="/Listing/GetByList?name=John&contact=calgary%2C%20vancouver">
<span>People</span>
</a>
which will successfully invoke the GetByList
controller action passing the two parameters:
public ActionResult GetByList(string name, string contact)
{
...
}
You aren't actually sending JSON. You are passing an object as the data
, but you need to stringify the object and pass the string instead.
Your dataType: "json"
only tells jQuery that you want it to parse the returned JSON, it does not mean that jQuery will automatically stringify your request data.
Change to:
$.ajax({
type: "POST",
url: hb_base_url + "consumer",
contentType: "application/json",
dataType: "json",
data: JSON.stringify({
first_name: $("#namec").val(),
last_name: $("#surnamec").val(),
email: $("#emailc").val(),
mobile: $("#numberc").val(),
password: $("#passwordc").val()
}),
success: function(response) {
console.log(response);
},
error: function(response) {
console.log(response);
}
});
Try this for Windows:
npm uninstall -g cordova
Try this for MAC:
sudo npm uninstall -g cordova
You can also add Cordova like this:
If You Want To install the previous version of Cordova through the Node Package Manager (npm):
npm install -g [email protected]
If You Want To install the latest version of Cordova:
npm install -g cordova
Enjoy!
Here is a simple example of multiple objects animation in a queue.
Jquery alow us to make queue over only one object. But within animation function we can access other objects. In this example we build our queue over #q object while animating #box1 and #box2 objects.
Think of queue as a array of functions. So you can manipulate queue as a array. You can use push, pop, unshift, shift to manipulate the queue. In this example we remove the last function from the animation queue and insert it at the beginning.
When we are done, we start animation queue by dequeue() function.
html:
<button id="show">Start Animation Queue</button>
<p></p>
<div id="box1"></div>
<div id="box2"></div>
<div id="q"></div>
js:
$(function(){
$('#q').queue('chain',function(next){
$("#box2").show("slow", next);
});
$('#q').queue('chain',function(next){
$('#box1').animate(
{left: 60}, {duration:1000, queue:false, complete: next}
)
});
$('#q').queue('chain',function(next){
$("#box1").animate({top:'200'},1500, next);
});
$('#q').queue('chain',function(next){
$("#box2").animate({top:'200'},1500, next);
});
$('#q').queue('chain',function(next){
$("#box2").animate({left:'200'},1500, next);
});
//notice that show effect comes last
$('#q').queue('chain',function(next){
$("#box1").show("slow", next);
});
});
$("#show").click(function () {
$("p").text("Queue length is: " + $('#q').queue("chain").length);
// remove the last function from the animation queue.
var lastFunc = $('#q').queue("chain").pop();
// insert it at the beginning:
$('#q').queue("chain").unshift(lastFunc);
//start animation queue
$('#q').dequeue('chain');
});
css:
#box1 { margin:3px; width:40px; height:40px;
position:absolute; left:10px; top:60px;
background:green; display: none; }
#box2 { margin:3px; width:40px; height:40px;
position:absolute; left:100px; top:60px;
background:red; display: none; }
p { color:red; }
This worked for me:
python3 -m venv env
source ./env/bin/activate
python -m pip install package
(From Github: https://github.com/googlesamples/assistant-sdk-python/issues/236 )
Performance test for in_array vs array_intersect:
$a1 = array(2,4,8,11,12,13,14,15,16,17,18,19,20);
$a2 = array(3,20);
$intersect_times = array();
$in_array_times = array();
for($j = 0; $j < 10; $j++)
{
/***** TEST ONE array_intersect *******/
$t = microtime(true);
for($i = 0; $i < 100000; $i++)
{
$x = array_intersect($a1,$a2);
$x = empty($x);
}
$intersect_times[] = microtime(true) - $t;
/***** TEST TWO in_array *******/
$t2 = microtime(true);
for($i = 0; $i < 100000; $i++)
{
$x = false;
foreach($a2 as $v){
if(in_array($v,$a1))
{
$x = true;
break;
}
}
}
$in_array_times[] = microtime(true) - $t2;
}
echo '<hr><br>'.implode('<br>',$intersect_times).'<br>array_intersect avg: '.(array_sum($intersect_times) / count($intersect_times));
echo '<hr><br>'.implode('<br>',$in_array_times).'<br>in_array avg: '.(array_sum($in_array_times) / count($in_array_times));
exit;
Here are the results:
0.26520013809204
0.15600109100342
0.15599989891052
0.15599989891052
0.1560001373291
0.1560001373291
0.15599989891052
0.15599989891052
0.15599989891052
0.1560001373291
array_intersect avg: 0.16692011356354
0.015599966049194
0.031199932098389
0.031200170516968
0.031199932098389
0.031200885772705
0.031199932098389
0.031200170516968
0.031201124191284
0.031199932098389
0.031199932098389
in_array avg: 0.029640197753906
in_array is at least 5 times faster. Note that we "break" as soon as a result is found.
I would ALWAYS go with both the alt
and the title
attributes. Many developers have been using this pattern now for over 20 years to deal with IE and other issues. So this is not new knowledge. Its just been rediscovered by new developers that didn't bother to learn from the past.
In addition, in HTML5 you should start using the new HTML5 picture
element wrapped in figure
with full WPA-ARIA attributes for greater accessibility, as well as support of assistive technologies, screen readers, and the like. Because this element is not supported in many older browsers...BUT degrades gracefully...I recommend the following HTML design pattern now for images in HTML:
<figure aria-labelledby="picturecaption2">
<picture id="picture2">
<source srcset="image.webp" type="image/webp" media="(min-width: 800px)" />
<source srcset="image.gif" type="image/gif" />
<img id="image2" style="height:auto;max-width: 100%;" src="image.jpg" width="255" height="200" alt="image:The World Wide Web" title="The World Wide Web" loading="lazy" no-referrer="no-referrer" onerror="this.onerror=null;" />
</picture>
<figcaption id="picturecaption2"><small>"My Cool Picture" [<a href="http://creativecommons.org/licenses/" target="_blank">A License</a>] , via <a href="https://commons.wikimedia.org/wiki/" target="_blank">Wikimedia Commons</a></small></figcaption>
</figure>
The code above has many extra "goodies" beside alt
and title
, including ARIA attributes, support for WebP, a media query supporting higher resolution imagery, and a nice fallback pattern supporting older image formats. It shows a fully decorated image example that uses new technologies while still supporting old ones with progressive design patterns.
REMEMBER...ALWAYS SUPPORT THE OLD BROWSERS!
Based on this article I found this method easier for my usecase.
My 'dev' branch was ahead of 'origin/dev' by 96 commits (so these commits were not pushed to the remote yet).
I wanted to squash these commits into one before pushing the change. I prefere to reset the branch to the state of 'origin/dev' (this will leave all changes from the 96 commits unstaged) and then commit the changes at once:
git reset origin/dev
git add --all
git commit -m 'my commit message'
I'd recommend this article on CSS Tricks by Chris Coyier entitled Better Helvetica:
http://css-tricks.com/snippets/css/better-helvetica/
He basically recommends the following declaration for covering all the bases:
body {
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
font-weight: 300;
}
you are getting math domain error for either one of the reason : either you are trying to use a negative number inside log function or a zero value.
Based on SFEley's answer, here is an updated/fixed one for newer Rails versions:
class SetDefault < ActiveRecord::Migration
def change
change_column :table_name, :column_name, :type, default: "Your value"
end
end
As of April 2018, Chrome (along with several other major browsers) now require the muted
attribute too.
Therefore, you should use
<video width="320" height="240" autoplay loop muted>
<source src="movie.mp4" type="video/mp4" />
</video>
[Edit] After reviewing the Mongoose documentation, it looks like you can send each query result as a separate chunk; the web server uses chunked transfer encoding by default so all you have to do is wrap an array around the items to make it a valid JSON object.
Roughly (untested):
app.get('/users/:email/messages/unread', function(req, res, next) {
var firstItem=true, query=MessageInfo.find(/*...*/);
res.writeHead(200, {'Content-Type': 'application/json'});
query.each(function(docs) {
// Start the JSON array or separate the next element.
res.write(firstItem ? (firstItem=false,'[') : ',');
res.write(JSON.stringify({ msgId: msg.fileName }));
});
res.end(']'); // End the JSON array and response.
});
Alternatively, as you mention, you can simply send the array contents as-is. In this case the response body will be buffered and sent immediately, which may consume a large amount of additional memory (above what is required to store the results themselves) for large result sets. For example:
// ...
var query = MessageInfo.find(/*...*/);
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(query.map(function(x){ return x.fileName })));
Sameer:
float l = new Float(x/y)
will not work, as it will compute integer division of x and y first, then construct a float from it.
float result = (float) x / (float) y;
Is semantically the best candidate.
Difference between UTF-8 and UTF-16? Why do we need these?
There have been at least a couple of security vulnerabilities in implementations of UTF-16. See Wikipedia for details.
WHATWG and W3C have now declared that only UTF-8 is to be used on the Web.
The [security] problems outlined here go away when exclusively using UTF-8, which is one of the many reasons that is now the mandatory encoding for all things.
Other groups are saying the same.
So while UTF-16 may continue being used internally by some systems such as Java and Windows, what little use of UTF-16 you may have seen in the past for data files, data exchange, and such, will likely fade away entirely.
Just wanted to share my solution using sqlalchemy and pandas in python 3. Perhaps, one would find it useful.
import sqlalchemy as sa
import pandas as pd
engine = sa.create_engine("postgresql://postgres:my_password@my_host:my_port/my_db")
values = [val1,val2,val3]
query = sa.text("""
SELECT *
FROM my_table
WHERE col1 IN :values;
""")
query = query.bindparams(values=tuple(values))
df = pd.read_sql(query, engine)
If you want to check the validity and consistency of all the existing views you can use the following query
declare @viewName sysname
declare @cmd sysname
DECLARE check_cursor CURSOR FOR
SELECT cast('['+SCHEMA_NAME(schema_id)+'].['+name+']' as sysname) AS viewname
FROM sys.views
OPEN check_cursor
FETCH NEXT FROM check_cursor
INTO @viewName
WHILE @@FETCH_STATUS = 0
BEGIN
set @cmd='select * from '+@viewName
begin try
exec (@cmd)
end try
begin catch
print 'Error: The view '+@viewName+' is corrupted .'
end catch
FETCH NEXT FROM check_cursor
INTO @viewName
END
CLOSE check_cursor;
DEALLOCATE check_cursor;
This feature is not supported in version 4. You can still use it via -c tessedit_char_whitelist=0123456789 with "--oem 0" which reverts to the old model.
There is a bounty to fix this issue.
Possible workarounds:
As stated by @amitdo
Start by hiding in OnResume() of the activity then also keep hiding as shown below:
decorView.setOnSystemUiVisibilityChangeListener
(new View.OnSystemUiVisibilityChangeListener() {
@Override
public void onSystemUiVisibilityChange(int visibility) {
// Note that system bars will only be "visible" if none of the
// LOW_PROFILE, HIDE_NAVIGATION, or FULLSCREEN flags are set.
if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
//visible
hideSystemUI();
}
}
}
});`
public void hideSystemUI() {
// Set the IMMERSIVE flag.
// Set the content to appear under the system bars so that the content
// doesn't resize when the system bars hide and show.
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
| View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
| View.SYSTEM_UI_FLAG_IMMERSIVE);
}
It's more an advice than answer, but if you are using a Spring MVC in your web application the good idea is to use Spring HandlerInterceptor instead of Filter
It can do the same job, but also
- Can work with ModelAndView
- Its methods can be called before and after request processing, or after request completion.
- It can be easily tested
1 Implement HandlerInterceptor interface and add a @Component annotation to your class
@Component
public class SecurityInterceptor implements HandlerInterceptor {
private static Logger log = LoggerFactory.getLogger(SecurityInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
request.getSession(true);
if(isLoggedIn(request))
return true;
response.getWriter().write("{\"loggedIn\":false}");
return false;
}
private boolean isLoggedIn(HttpServletRequest request) {
try {
UserSession userSession = (UserSession) request.getSession(true).getAttribute("userSession");
return userSession != null && userSession.isLoggedIn();
} catch(IllegalStateException ex) {
return false;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
}
}
2 Configure your Interceptor
@Configuration
public class WebConfig implements WebMvcConfigurer {
private HandlerInterceptor securityInterceptor;
@Autowired
public void setSecurityInterceptor(HandlerInterceptor securityInterceptor) {
this.securityInterceptor = securityInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(securityInterceptor).addPathPatterns("/**").excludePathPatterns("/login", "/logout");
}
}
After several hours of test and research over the Internet, I've finally found how to start my PowerShell script with task scheduler, thanks to the video Scheduling a PowerShell Script using Windows Task Scheduler by Jack Fruh @sharepointjack.
Program/script -> put full path through powershell.exe
C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe
Add arguments -> Full path to the script, and the script, without any " ".
Start in (optional) -> The directory where your script resides, without any " ".
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div
= document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i <
a.length; i++) {
txtValue = a[i].textContent || a[i].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}
_x000D_
#myInput {
box-sizing: border-box;
background-image: url('searchicon.png');
background-position: 14px 12px;
background-repeat: no-repeat;
font-size: 16px;
padding: 14px 20px 12px 45px;
border: none;
border-bottom: 1px solid #ddd;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f6f6f6;
min-width: 230px;
overflow: auto;
border: 1px solid #ddd;
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {
background-color: #ddd;
}
.show {
display: block;
}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
<a href="#about">home</a>
<a href="#base">contact</a>
</div>
</div>
_x000D_
Having the following XML:
<node>Text1<subnode/>text2</node>
How do I select either the first or the second text node via XPath?
Use:
/node/text()
This selects all text-node children of the top element (named "node") of the XML document.
/node/text()[1]
This selects the first text-node child of the top element (named "node") of the XML document.
/node/text()[2]
This selects the second text-node child of the top element (named "node") of the XML document.
/node/text()[someInteger]
This selects the someInteger-th text-node child of the top element (named "node") of the XML document. It is equivalent to the following XPath expression:
/node/text()[position() = someInteger]
Use this XPath expression:
/*/*/X/node()
This selects any node (element, text node, comment or processing instruction) that is a child of any X
element that is a grand-child of the top element of the XML document.
To verify what is selected, here is this XSLT transformation that outputs exactly the selected nodes:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="/">
<xsl:copy-of select="/*/*/X/node()"/>
</xsl:template>
</xsl:stylesheet>
and it produces exactly the wanted, correct result:
First Text Node #1
<y> Y can Have Child Nodes #
<child> deep to it </child>
</y> Second Text Node #2
<z />
Explanation:
As defined in the W3 XPath 1.0 Spec, "child::node()
selects all the children of the context node, whatever their node type." This means that any element, text-node, comment-node and processing-instruction node children are selected by this node-test.
node()
is an abbreviation of child::node()
(because child::
is the primary axis and is used when no axis is explicitly specified).
You can use the Conditional Formatting to replace text and NOT effect any formulas. Simply go to the Rule's format where you will see Number, Font, Border and Fill.
Go to the Number tab and select CUSTOM
. Then simply type where it says TYPE
: what you want to say in QUOTES.
Example.. "OTHER"
Here's a wrapper to pretty-fy it if you need it:
(function() {
var originalSetInterval = window.setInterval;
window.setInterval = function(fn, delay, runImmediately) {
if(runImmediately) fn();
return originalSetInterval(fn, delay);
};
})();
Set the third argument of setInterval to true and it'll run for the first time immediately after calling setInterval:
setInterval(function() { console.log("hello world"); }, 5000, true);
Or omit the third argument and it will retain its original behaviour:
setInterval(function() { console.log("hello world"); }, 5000);
Some browsers support additional arguments for setInterval which this wrapper doesn't take into account; I think these are rarely used, but keep that in mind if you do need them.
Horizontal and Vertical center alignment
<View style={{flex: 1, justifyContent: 'center',alignItems: 'center'}}>
<Text> Example Test </Text>
</View>
Another way to do this is by using a "configure" script. If you are already using one with your makefile, you can use a combination of uname and sed to get things to work out. First, in your script, do:
UNAME=uname
Then, in order to put this in your Makefile, start out with Makefile.in which should have something like
UNAME=@@UNAME@@
in it.
Use the following sed command in your configure script after the UNAME=uname
bit.
sed -e "s|@@UNAME@@|$UNAME|" < Makefile.in > Makefile
Now your makefile should have UNAME
defined as desired. If/elif/else statements are all that's left!
So, what's wrong with checking each element iteratively?
function arraysEqual(arr1, arr2) {
if(arr1.length !== arr2.length)
return false;
for(var i = arr1.length; i--;) {
if(arr1[i] !== arr2[i])
return false;
}
return true;
}
In case it helps others, I got this error when the service the task was running at didn't have write permission to the executable location. It was attempting to write a log file there.
Source for the Data warehouse can be cluster of Databases, because databases are used for Online Transaction process like keeping the current records..but in Data warehouse it stores historical data which are for Online analytical process.
very basic:
<?php
$username = 'user';
$password = 'password';
$server = 'localhost';
// Opens a connection to a MySQL server
$connection = mysql_connect ($server, $username, $password) or die('try again in some minutes, please');
//if you want to suppress the error message, substitute the connection line for:
//$connection = @mysql_connect($server, $username, $password) or die('try again in some minutes, please');
?>
result:
Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'user'@'localhost' (using password: YES) in /home/user/public_html/zdel1.php on line 6 try again in some minutes, please
as per Wrikken's recommendation below, check out a complete error handler for more complex, efficient and elegant solutions: http://www.php.net/manual/en/function.set-error-handler.php
class ArrayPrinter
{
#region Declarations
static bool isLeftAligned = false;
const string cellLeftTop = "+";
const string cellRightTop = "+";
const string cellLeftBottom = "+";
const string cellRightBottom = "+";
const string cellHorizontalJointTop = "-";
const string cellHorizontalJointbottom = "-";
const string cellVerticalJointLeft = "+";
const string cellTJoint = "+";
const string cellVerticalJointRight = "¦";
const string cellHorizontalLine = "-";
const string cellVerticalLine = "¦";
#endregion
#region Private Methods
private static int GetMaxCellWidth(string[,] arrValues)
{
int maxWidth = 1;
for (int i = 0; i < arrValues.GetLength(0); i++)
{
for (int j = 0; j < arrValues.GetLength(1); j++)
{
int length = arrValues[i, j].Length;
if (length > maxWidth)
{
maxWidth = length;
}
}
}
return maxWidth;
}
private static string GetDataInTableFormat(string[,] arrValues)
{
string formattedString = string.Empty;
if (arrValues == null)
return formattedString;
int dimension1Length = arrValues.GetLength(0);
int dimension2Length = arrValues.GetLength(1);
int maxCellWidth = GetMaxCellWidth(arrValues);
int indentLength = (dimension2Length * maxCellWidth) + (dimension2Length - 1);
//printing top line;
formattedString = string.Format("{0}{1}{2}{3}", cellLeftTop, Indent(indentLength), cellRightTop, System.Environment.NewLine);
for (int i = 0; i < dimension1Length; i++)
{
string lineWithValues = cellVerticalLine;
string line = cellVerticalJointLeft;
for (int j = 0; j < dimension2Length; j++)
{
string value = (isLeftAligned) ? arrValues[i, j].PadRight(maxCellWidth, ' ') : arrValues[i, j].PadLeft(maxCellWidth, ' ');
lineWithValues += string.Format("{0}{1}", value, cellVerticalLine);
line += Indent(maxCellWidth);
if (j < (dimension2Length - 1))
{
line += cellTJoint;
}
}
line += cellVerticalJointRight;
formattedString += string.Format("{0}{1}", lineWithValues, System.Environment.NewLine);
if (i < (dimension1Length - 1))
{
formattedString += string.Format("{0}{1}", line, System.Environment.NewLine);
}
}
//printing bottom line
formattedString += string.Format("{0}{1}{2}{3}", cellLeftBottom, Indent(indentLength), cellRightBottom, System.Environment.NewLine);
return formattedString;
}
private static string Indent(int count)
{
return string.Empty.PadLeft(count, '-');
}
#endregion
#region Public Methods
public static void PrintToStream(string[,] arrValues, StreamWriter writer)
{
if (arrValues == null)
return;
if (writer == null)
return;
writer.Write(GetDataInTableFormat(arrValues));
}
public static void PrintToConsole(string[,] arrValues)
{
if (arrValues == null)
return;
Console.WriteLine(GetDataInTableFormat(arrValues));
}
#endregion
static void Main(string[] args)
{
int value = 997;
string[,] arrValues = new string[5, 5];
for (int i = 0; i < arrValues.GetLength(0); i++)
{
for (int j = 0; j < arrValues.GetLength(1); j++)
{
value++;
arrValues[i, j] = value.ToString();
}
}
ArrayPrinter.PrintToConsole(arrValues);
Console.ReadLine();
}
}
You can perform a simple each
loop on the range from 1 to `x´:
(1..x).each do |i|
#...
end
Your looking for the onSelect event in the datepicker object:
$('.selector').datepicker({
onSelect: function(dateText, inst) { ... }
});
display: inline-block
is your friend you just need all three parts of the construct - before, the "block", after - to be one, then you can vertically align them all to the middle:
(it looks like your picture anyway ;))
CSS:
p, div {
display: inline-block;
vertical-align: middle;
}
p, div {
display: inline !ie7; /* hack for IE7 and below */
}
table {
background: #000;
color: #fff;
font-size: 16px;
font-weight: bold; margin: 0 10px;
}
td {
padding: 5px;
text-align: center;
}
HTML:
<p>some text</p>
<div>
<table summary="">
<tr><td>A</td></tr>
<tr><td>B</td></tr>
<tr><td>C</td></tr>
<tr><td>D</td></tr>
</table>
</div>
<p>continues afterwards</p>
You could use android:editable="false"
but I would really advise you
to use setEnabled(false)
as it provides a visual clue to the user that
the control cannot be edited. The same visual cue is used by all
disabled widgets and consistency is good.
As another anwsers told, you can change in a Session Listener. But you can change it directly in your servlet, for example.
getRequest().getSession().setMaxInactiveInterval(123);
Python variables are scoped to the innermost function, class, or module in which they're assigned. Control blocks like if
and while
blocks don't count, so a variable assigned inside an if
is still scoped to a function, class, or module.
(Implicit functions defined by a generator expression or list/set/dict comprehension do count, as do lambda expressions. You can't stuff an assignment statement into any of those, but lambda parameters and for
clause targets are implicit assignment.)
To expand upon Mr. Eels comment, you can do it like this:
File file = new File("C:\\A.txt");
FileWriter writer;
try {
writer = new FileWriter(file, true);
PrintWriter printer = new PrintWriter(writer);
printer.append("Sue");
printer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Don't say we ain't good to ya!
Array indexes in JavaScript start at zero for the first item, so try this:
var firstArrayItem = myValues[0]
Of course, if you actually want the second item in the array at index 1, then it's myValues[1]
.
See Accessing array elements for more info.
You can define foreign key by:
public class Parent
{
public int Id { get; set; }
public virtual ICollection<Child> Childs { get; set; }
}
public class Child
{
public int Id { get; set; }
// This will be recognized as FK by NavigationPropertyNameForeignKeyDiscoveryConvention
public int ParentId { get; set; }
public virtual Parent Parent { get; set; }
}
Now ParentId is foreign key property and defines required relation between child and existing parent. Saving the child without exsiting parent will throw exception.
If your FK property name doesn't consists of the navigation property name and parent PK name you must either use ForeignKeyAttribute data annotation or fluent API to map the relation
Data annotation:
// The name of related navigation property
[ForeignKey("Parent")]
public int ParentId { get; set; }
Fluent API:
modelBuilder.Entity<Child>()
.HasRequired(c => c.Parent)
.WithMany(p => p.Childs)
.HasForeignKey(c => c.ParentId);
Other types of constraints can be enforced by data annotations and model validation.
Edit:
You will get an exception if you don't set ParentId
. It is required property (not nullable). If you just don't set it it will most probably try to send default value to the database. Default value is 0 so if you don't have customer with Id = 0 you will get an exception.
Try this, you can parse nested JSON
public static String getJsonValue(String jsonReq, String key) {
JSONObject json = new JSONObject(jsonReq);
boolean exists = json.has(key);
Iterator<?> keys;
String nextKeys;
String val = "";
if (!exists) {
keys = json.keys();
while (keys.hasNext()) {
nextKeys = (String) keys.next();
try {
if (json.get(nextKeys) instanceof JSONObject) {
return getJsonValue(json.getJSONObject(nextKeys).toString(), key);
} else if (json.get(nextKeys) instanceof JSONArray) {
JSONArray jsonArray = json.getJSONArray(nextKeys);
int i = 0;
if (i < jsonArray.length()) do {
String jsonArrayString = jsonArray.get(i).toString();
JSONObject innerJson = new JSONObject(jsonArrayString);
return getJsonValue(innerJson.toString(),key);
} while (i < jsonArray.length());
}
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
val = json.get(key).toString();
}
return val;
}
--- Update Angular 9 and Rxjs 6 Solution
unsubscribe
at ngDestroy
lifecycle of Angular Componentclass SampleComponent implements OnInit, OnDestroy {
private subscriptions: Subscription;
private sampleObservable$: Observable<any>;
constructor () {}
ngOnInit(){
this.subscriptions = this.sampleObservable$.subscribe( ... );
}
ngOnDestroy() {
this.subscriptions.unsubscribe();
}
}
takeUntil
in Rxjsclass SampleComponent implements OnInit, OnDestroy {
private unsubscribe$: new Subject<void>;
private sampleObservable$: Observable<any>;
constructor () {}
ngOnInit(){
this.subscriptions = this.sampleObservable$
.pipe(takeUntil(this.unsubscribe$))
.subscribe( ... );
}
ngOnDestroy() {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
}
ngOnInit
that just happen only one time when component init.class SampleComponent implements OnInit {
private sampleObservable$: Observable<any>;
constructor () {}
ngOnInit(){
this.subscriptions = this.sampleObservable$
.pipe(take(1))
.subscribe( ... );
}
}
We also have async
pipe. But, this one use on the template (not in Angular component).
I did it this way with Bootstrap 4.3.1
:
<div class="d-flex vh-100">
<div class="d-flex w-100 justify-content-center align-self-center">
I'm in the middle
</div>
</div>
There is another useful method called AutoResizeColumn
which allows you to auto size a specific column with the required parameter.
You can call it like this:
listview1.AutoResizeColumn(1, ColumnHeaderAutoResizeStyle.ColumnContent);
listview1.AutoResizeColumn(2, ColumnHeaderAutoResizeStyle.ColumnContent);
listview1.AutoResizeColumn(3, ColumnHeaderAutoResizeStyle.HeaderSize);
listview1.AutoResizeColumn(4, ColumnHeaderAutoResizeStyle.HeaderSize);
I used this to sort a gallery of images where the sort array would be altered by an ajax call. Hopefully it can be useful to someone.
var myArray = ['2', '3', '1'];_x000D_
var elArray = [];_x000D_
_x000D_
$('.imgs').each(function() {_x000D_
elArray[$(this).data('image-id')] = $(this);_x000D_
});_x000D_
_x000D_
$.each(myArray,function(index,value){_x000D_
$('#container').append(elArray[value]); _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
<div id='container'>_x000D_
<div class="imgs" data-image-id='1'>1</div>_x000D_
<div class="imgs" data-image-id='2'>2</div>_x000D_
<div class="imgs" data-image-id='3'>3</div>_x000D_
</div>
_x000D_
Fiddle: http://jsfiddle.net/ruys9ksg/
Specific type of array in typescript
export class RegisterFormComponent
{
genders = new Array<GenderType>(); // Use any array supports different kind objects
loadGenders()
{
this.genders.push({name: "Male",isoCode: 1});
this.genders.push({name: "FeMale",isoCode: 2});
}
}
type GenderType = { name: string, isoCode: number }; // Specified format
Button button = new Button();
button.Click += (s,e) => { your code; };
//button.Click += new EventHandler(button_Click);
container.Controls.Add(button);
//protected void button_Click (object sender, EventArgs e) { }
Why don't you try to grep the return of your command ? Something like :
adb devices -l | grep 123abc12
It should return only the line you want to.
Yes, the task gets blocked in the read() system call. Another task which is ready runs, or if no other tasks are ready, the idle task (for that CPU) runs.
A normal, blocking disc read causes the task to enter the "D" state (as others have noted). Such tasks contribute to the load average, even though they're not consuming the CPU.
Some other types of IO, especially ttys and network, do not behave quite the same - the process ends up in "S" state and can be interrupted and doesn't count against the load average.
SELECT 'DROP TABLE "' || TABLE_NAME || '" CASCADE CONSTRAINTS;'
FROM user_tables;
user_tables
is a system table which contains all the tables of the user
the SELECT clause will generate a DROP statement for every table
you can run the script
As mentioned by other folks, the variable length of the string is the issue.
Rather than reinventing the wheel, Apache Commons has a nice, clean solution for this in StringUtils.
StringUtils.rightPad("String to extend",100); //100 is the length you want to pad out to.
You need to take out your suffix rule (%.o: %.c) in favour of a big-bang rule. Something like this:
LIBS = -lkernel32 -luser32 -lgdi32 -lopengl32
CFLAGS = -Wall
OBJ = 64bitmath.o \
monotone.o \
node_sort.o \
planesweep.o \
triangulate.o \
prim_combine.o \
welding.o \
test.o \
main.o
SRCS = $(OBJ:%.o=%.c)
test: $(SRCS)
gcc -o $@ $(CFLAGS) $(LIBS) $(SRCS)
If you're going to experiment with GCC's whole-program optimization, make sure that you add the appropriate flag to CFLAGS, above.
On reading through the docs for those flags, I see notes about link-time optimization as well; you should investigate those too.
The two structs are different. When you initialize the first struct, about 40 bytes of memory are allocated. When you initialize the second struct, about 10 bytesof memory are allocated. (Actual amount is architecture dependent)
You can use the string literals (string constants) to initalize character arrays. This is why
person p = {"John", "Doe",30};
works in the first example.
You cannot assign (in the conventional sense) a string in C.
The string literals you have ("John") are loaded into memory when your code executes. When you initialize an array with one of these literals, then the string is copied into a new memory location. In your second example, you are merely copying the pointer to (location of) the string literal. Doing something like:
char* string = "Hello";
*string = 'C'
might cause compile or runtime errors (I am not sure.) It is a bad idea because you are modifying the literal string "Hello" which, for example on a microcontroler, could be located in read-only memory.
Generally speaking, don't. If you are nesting "ifs" and breaking from them, you are doing it wrong.
However, if you must:
if condition_a:
def condition_a_fun():
do_stuff()
if we_wanna_escape:
return
condition_a_fun()
if condition_b:
def condition_b_fun():
do_more_stuff()
if we_wanna_get_out_again:
return
condition_b_fun()
Note, the functions don't HAVE to be declared in the if statement, they can be declared in advance ;) This would be a better choice, since it will avoid needing to refactor out an ugly if/then later on.
I built my solution on top of @aditya Prakash appraoch:
print(re.search("^([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])(\.|-|/)([1-9]|0[1-9]|1[0-2])(\.|-|/)([0-9][0-9]|19[0-9][0-9]|20[0-9][0-9])$|^([0-9][0-9]|19[0-9][0-9]|20[0-9][0-9])(\.|-|/)([1-9]|0[1-9]|1[0-2])(\.|-|/)([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])$",'01/01/2018'))
The first part (^([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])(\.|-|/)([1-9]|0[1-9]|1[0-2])(\.|-|/)([0-9][0-9]|19[0-9][0-9]|20[0-9][0-9])$
) can handle the following formats:
The second part (^([0-9][0-9]|19[0-9][0-9]|20[0-9][0-9])(\.|-|/)([1-9]|0[1-9]|1[0-2])(\.|-|/)([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])$
) can basically do the same, but in inverse order, where the year comes first, followed by month, and then day.
As delimiters it allows ., /, -. As years it allows everything from 1900-2099, also giving only two numbers is fine.
If you have suggestions for improvement please let me know in the comments, so I can update the answer.
ES6 of the day here;
const json_getAllKeys = data => (
data.reduce((keys, obj) => (
keys.concat(Object.keys(obj).filter(key => (
keys.indexOf(key) === -1))
)
), [])
)
And yes it can be written in very long one line;
const json_getAllKeys = data => data.reduce((keys, obj) => keys.concat(Object.keys(obj).filter(key => keys.indexOf(key) === -1)), [])
EDIT: Returns all first order keys if the input is of type array of objects
Linux users can find the locations of all the installed packages like this:
pip list | xargs -exec pip show
<a href="#nogo">My Link</a>
Before running nodemon, Please start mongod first. You will never get this error. :)
below solution worked for me in case of required number is float. Solution:
table=sorted(table,key=lambda x: float(x[5]))
for row in table[:]:
Ntable.add_row(row)
'
See X-Frame-Options header on error response
You can simply add following line to .htaccess
Header always unset X-Frame-Options
Try setting your font from the menu and then typing
:set guifont?
This should display to you the string that Vim has set this option to. You'll need to escape any spaces.
In Windows 7 I did this:
Done!
Yeah, IsNumeric is VB. Usually people use the TryParse() method, though it is a bit clunky. As you suggested, you can always write your own.
int i;
if (int.TryParse(string, out i))
{
}
If you want the view to be read only after granting the read permission you can use the ALGORITHM = TEMPTABLE in you view DDL definition.
You are missing 'json' dataType in the $.post()
method:
$.post('http://www.example.com:PORT_NUMBER/MYSERVLET',{MyParam: 'value'})
.done(function(data){
alert(data);
}, "json");
//-^^^^^^-------here
Updates:
try with this:
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
getline
, as it name states, read a whole line, or at least till a delimiter that can be specified.
So the answer is "no", getline
does not match your need.
But you can do something like:
inFile >> first_name >> last_name >> age;
name = first_name + " " + last_name;
The addition of a string literal with an std::string
yields another std::string
. system
expects a const char*
. You can use std::string::c_str()
for that:
string name = "john";
string tmp = " quickscan.exe resolution 300 selectscanner jpg showui showprogress filename '"+name+".jpg'"
system(tmp.c_str());
New XCode 7 will only require 'UIFileSharingEnabled' key in Info.plist. 'CFBundleDisplayName' is not required any more.
One more hint: do not only modify the Info.plist of the 'tests' target. The main app and the 'tests' have different Info.plist.
Best way to do this is to use a function:
<div ng-repeat="product in products | filter: myFilter">
$scope.myFilter = function (item) {
return item === 'red' || item === 'blue';
};
Alternatively, you can use ngHide or ngShow to dynamically show and hide elements based on a certain criteria.
I was looking to do the same thing, but to preserve the list as a just an array of strings so I wrote a new code, which from what I've been reading may not be the most efficient but worked for what i needed to do:
combineListsAsOne <-function(list1, list2){
n <- c()
for(x in list1){
n<-c(n, x)
}
for(y in list2){
n<-c(n, y)
}
return(n)
}
It just creates a new list and adds items from two supplied lists to create one.
Yea, it's bad...
==
means that your two string references are exactly the same object. You may have heard that this is the case because Java keeps sort of a literal table (which it does), but that is not always the case. Some strings are loaded in different ways, constructed from other strings, etc., so you must never assume that two identical strings are stored in the same location.
Equals does the real comparison for you.
To search for specifil file types in visual studio code.
Type ctrl+p and then search for something like *.py.
Simple and easy
I just installed the 32bit 11g R2 Express edition version on 64bit windows, created a new database and performed some queries. Seems to work like it should work! :-) I followed the following easy guide!
Resharper is good for this like others have stated. Be careful though, these tools don't find you code that is used by reflection, e.g. cannot know if some code is NOT used by reflection.
To get mod_rewrite to work for me in Apache 2.4, I had to add the "Require all granted" line below.
<Directory /var/www>
# Required if running apache > 2.4
Require all granted
RewriteEngine on
RewriteRule ^cachebust-([a-z0-9]+)\/(.*) /$2 [L]
</Directory>
supposedly a similar requirement exists for Apache 2.2 as well, if you're using that:
<Directory /var/www>
# Required if running apache 2.2
Order allow,deny
Allow from all
RewriteEngine on
RewriteRule ^cachebust-([a-z0-9]+)\/(.*) /$2 [L]
</Directory>
Note that an ErrorDocument 404
directive can sometimes override these things as well, so if it's not working try commenting out your ErrorDocument directive and see if it works. The above example can be used to ensure a site isn't served from cache by including a subfolder in the path, though the files reside at the root of the server.
The interpretation of the backspace and carriage return characters is left to the software you use for display. A terminal emulator, when displaying \b would move the cursor one step back, and when displaying \r to the beginning of the line. If you print these characters somewhere else, like a text file, the software may choose. to do something else.
You can also get information from directly connected networking devices, such as network switches with LDWin, a portable and free Windows program published on github:
http://www.sysadmit.com/2016/11/windows-como-saber-la-ip-del-switch-al-que-estoy-conectado.html
LDWin supports the following methods of link discovery: CDP (Cisco Discovery Protocol) and LLDP (Link Layer Discovery Protocol).
You can obtain the model, management IP, VLAN identifier, Port identifier, firmware version, etc.
CONVERT
takes the column name, not a string containing the column name; your current expression tries to convert the string A.my_NvarcharColumn
to an integer instead of the column content.
SELECT convert (int, N'A.my_NvarcharColumn') FROM A;
should instead be
SELECT convert (int, A.my_NvarcharColumn) FROM A;
Simple SQLfiddle here.
boolean compare(String str1, String str2) {
return (str1==null || str2==null) ? str1 == str2 : str1.equals(str2);
}
You could kill all connections before dropping the database using the pg_terminate_backend(int)
function.
You can get all running backends using the system view pg_stat_activity
I'm not entirely sure, but the following would probably kill all sessions:
select pg_terminate_backend(procpid)
from pg_stat_activity
where datname = 'doomed_database'
Of course you may not be connected yourself to that database
I just did this out of interest. I agree it's not the right thing to do, but I think it should be the op's decision... Also the code could easily be extended to add functionality, rather than take it away (like a more advanced clipboard, or Ctrl+s triggering a server-side save).
$(document).ready(function() {_x000D_
var ctrlDown = false,_x000D_
ctrlKey = 17,_x000D_
cmdKey = 91,_x000D_
vKey = 86,_x000D_
cKey = 67;_x000D_
_x000D_
$(document).keydown(function(e) {_x000D_
if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = true;_x000D_
}).keyup(function(e) {_x000D_
if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = false;_x000D_
});_x000D_
_x000D_
$(".no-copy-paste").keydown(function(e) {_x000D_
if (ctrlDown && (e.keyCode == vKey || e.keyCode == cKey)) return false;_x000D_
});_x000D_
_x000D_
// Document Ctrl + C/V _x000D_
$(document).keydown(function(e) {_x000D_
if (ctrlDown && (e.keyCode == cKey)) console.log("Document catch Ctrl+C");_x000D_
if (ctrlDown && (e.keyCode == vKey)) console.log("Document catch Ctrl+V");_x000D_
});_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<h3>Ctrl+c Ctrl+v disabled</h3>_x000D_
<textarea class="no-copy-paste"></textarea>_x000D_
<br><br>_x000D_
<h3>Ctrl+c Ctrl+v allowed</h3>_x000D_
<textarea></textarea>
_x000D_
Also just to clarify, this script requires the jQuery library.
EDIT: removed 3 redundant lines (involving e.which) thanks to Tim Down's suggestion (see comments)
EDIT: added support for Macs (cmd key instead of ctrl)
Another flexible way using classpath containing fat jar (-cp fat.jar) or all jars (-cp "$JARS_DIR/*") and another custom config classpath or folder containing configuration files usually elsewhere and outside jar. So instead of the limited java -jar, use the more flexible classpath way as follows:
java \
-cp fat_app.jar \
-Dloader.path=<path_to_your_additional_jars or config folder> \
org.springframework.boot.loader.PropertiesLauncher
See Spring-boot executable jar doc and this link
If you do have multiple MainApps which is common, you can use How do I tell Spring Boot which main class to use for the executable jar?
You can add additional locations by setting an environment variable LOADER_PATH or loader.path in loader.properties (comma-separated list of directories, archives, or directories within archives). Basically loader.path works for both java -jar or java -cp way.
And as always you can override and exactly specify the application.yml it should pickup for debugging purpose
--spring.config.location=/some-location/application.yml --debug
Instead of .each, another (perhaps more concise) approach to getting all those prices might be:
var prices = $(products).children("li").map(function() {
return $(this).prop("data-price");
}).get();
additionally you may want to consider filtering the array to get rid of empty or non-numeric array values in case they should exist:
prices = prices.filter(function(n){ return(!isNaN(parseFloat(n))) });
then use Sergey's solution above:
var max = Math.max.apply(Math,prices);
var min = Math.min.apply(Math,prices);
You have to turn on the ability to add the formatter tags. In the menubar go to:
Windows → Preferences Java → Code Style → Formatter
Press the Edit button. Choose the last tab. Notice the On/Off box and enable them with a checkbox.
I also faced this same issue while working in my development environment, the problem was that I left host: localhost
commented out in the config/database.yml
file.
So my application could not connect to the PostgreSQL database, simply uncommenting it solved the issue.
development:
<<: *default
database: database_name
username: database_username
password: database_password
host: localhost
That's all.
I hope this helps
So here is a simple example of how to use classes: Suppose you are a finance institute. You want your customer's accounts to be managed by a computer. So you need to model those accounts. That is where classes come in. Working with classes is called object oriented programming. With classes you model real world objects in your computer. So, what do we need to model a simple bank account? We need a variable that saves the balance and one that saves the customers name. Additionally, some methods to in- and decrease the balance. That could look like:
class bankaccount():
def __init__(self, name, money):
self.name = name
self.money = money
def earn_money(self, amount):
self.money += amount
def withdraw_money(self, amount):
self.money -= amount
def show_balance(self):
print self.money
Now you have an abstract model of a simple account and its mechanism.
The def __init__(self, name, money)
is the classes' constructor. It builds up the object in memory. If you now want to open a new account you have to make an instance of your class. In order to do that, you have to call the constructor and pass the needed parameters. In Python a constructor is called by the classes's name:
spidermans_account = bankaccount("SpiderMan", 1000)
If Spiderman wants to buy M.J. a new ring he has to withdraw some money. He would call the withdraw
method on his account:
spidermans_account.withdraw_money(100)
If he wants to see the balance he calls:
spidermans_account.show_balance()
The whole thing about classes is to model objects, their attributes and mechanisms. To create an object, instantiate it like in the example. Values are passed to classes with getter and setter methods like `earn_money()´. Those methods access your objects variables. If you want your class to store another object you have to define a variable for that object in the constructor.
You can't use variable names to bind columns or other system objects, you need dynamic sql
DECLARE @value varchar(10)
SET @value = 'intStep'
DECLARE @sqlText nvarchar(1000);
SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)
Another option is to use JQuery to store the element's in-line style property, append to it, and to then update the element's style property with the new values. As follows:
function appendCSSToElement(element, CssProperties)
{
var existingCSS = $(element).attr("style");
if(existingCSS == undefined) existingCSS = "";
$.each(CssProperties, function(key,value)
{
existingCSS += " " + key + ": " + value + ";";
});
$(element).attr("style", existingCSS);
return $(element);
}
And then execute it with the new CSS attributes as an object.
appendCSSToElement("#ElementID", { "color": "white", "background-color": "green", "font-weight": "bold" });
This may not necessarily be the most efficient method (I'm open to suggestions on how to improve this. :) ), but it definitely works.
See if the below helps you:
I was using the following earlier:
ClientScript.RegisterClientScriptBlock(Page.GetType(), "AlertMsg", "<script language='javascript'>alert('The Web Policy need to be accepted to submit the new assessor information.');</script>");
After implementing AJAX in this page, it stopped working. After reading your blog, I changed the above to:
ScriptManager.RegisterClientScriptBlock(imgBtnSubmit, this.GetType(), "AlertMsg", "<script language='javascript'>alert('The Web Policy need to be accepted to submit the new assessor information.');</script>", false);
This is working perfectly fine.
(It’s .NET 2.0 Framework, I am using)
Element is not supported in IE8 out of the box you have to do some work to make IE8 accept custom tags.
One advantage of using an attribute over an element is that you can apply multiple directives to the same DOM node. This is particularly handy for things like form controls where you can highlight, disable, or add labels etc. with additional attributes without having to wrap the element in a bunch of tags.
A stub, in this context, means a mock implementation.
That is, a simple, fake implementation that conforms to the interface and is to be used for testing.
For my case, Xcode 8.2.1, I had a Map Kit View in a view controller. So I went to
Build Phases > Link Binary With Libraries
and added MapKit.framework
, then it was fine.
I think this will also apply to other views that require framework.
P.S. Running on iOS 9 told me that there was an issue about Map Kit View, while on iOS 10 told me nothing!
To create POM.XML file in Eclipse:
Install M2E plugin (http://www.eclipse.org/m2e/)
Right click on project -> Configure -> Convert to Maven Project
You can do it without a directive but i'm not sure it's the best way. To do this you must create array of array from the data you want to display in the table, and after that use 2 ng-repeat to iterate through the array.
to create the array for display use this function like that products.chunk(3)
Array.prototype.chunk = function(chunkSize) {
var array=this;
return [].concat.apply([],
array.map(function(elem,i) {
return i%chunkSize ? [] : [array.slice(i,i+chunkSize)];
})
);
}
and then do something like that using 2 ng-repeat
<div class="row" ng-repeat="row in products.chunk(3)">
<div class="col-sm4" ng-repeat="item in row">
{{item}}
</div>
</div>
Is there a way to limit a regex to 100 characters WITH regex?
Your example suggests that you'd like to grab a number from inside the regex and then use this number to place a maximum length on another part that is matched later in the regex. This usually isn't possible in a single pass. Your best bet is to have two separate regular expressions:
If you just want to limit the number of characters matched by an expression, most regular expressions support bounds by using braces. For instance,
\d{3}-\d{3}-\d{4}
will match (US) phone numbers: exactly three digits, then a hyphen, then exactly three digits, then another hyphen, then exactly four digits.
Likewise, you can set upper or lower limits:
\d{5,10}
means "at least 5, but not more than 10 digits".
Update: The OP clarified that he's trying to limit the value, not the length. My new answer is don't use regular expressions for that. Extract the value, then compare it against the maximum you extracted from the size parameter. It's much less error-prone.
Add this to the stylesheet:
table {
border-collapse: collapse;
}
The reason why it behaves this way is actually described pretty well in the specification:
There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.
... and later, for collapse
setting:
In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.
Use waitpid() like this:
pid_t childPid; // the child process that the execution will soon run inside of.
childPid = fork();
if(childPid == 0) // fork succeeded
{
// Do something
exit(0);
}
else if(childPid < 0) // fork failed
{
// log the error
}
else // Main (parent) process after fork succeeds
{
int returnStatus;
waitpid(childPid, &returnStatus, 0); // Parent process waits here for child to terminate.
if (returnStatus == 0) // Verify child process terminated without error.
{
printf("The child process terminated normally.");
}
if (returnStatus == 1)
{
printf("The child process terminated with an error!.");
}
}
Yes, H2 supports executing SQL statements when connecting. You could run a script, or just a statement or two:
String url = "jdbc:h2:mem:test;" +
"INIT=CREATE SCHEMA IF NOT EXISTS TEST"
String url = "jdbc:h2:mem:test;" +
"INIT=CREATE SCHEMA IF NOT EXISTS TEST\\;" +
"SET SCHEMA TEST";
String url = "jdbc:h2:mem;" +
"INIT=RUNSCRIPT FROM '~/create.sql'\\;" +
"RUNSCRIPT FROM '~/populate.sql'";
Please note the double backslash (\\
) is only required within Java. The backslash(es) before ;
within the INIT
is required.
First check - is the working directory the directory that the application is running in:
If this isn't the problem, then ask if Autodesk.Navisworks.Timeliner.dll is requiring another DLL which is not there.
If Timeliner.dll is not a .NET assembly, you can determine the required imports using the command utility DUMPBIN
.
dumpbin /imports Autodesk.Navisworks.Timeliner.dll
If it is a .NET assembly, there are a number of tools that can check dependencies.
Reflector
has already been mentioned, and I use JustDecompile
from Telerik.
After reading the answer from Gilles, I decided to see if the $BASH_COMMAND
var was also available (and the desired value) in an EXIT
trap - and it is!
So, the following bash script works as expected:
#!/bin/bash
exit_trap () {
local lc="$BASH_COMMAND" rc=$?
echo "Command [$lc] exited with code [$rc]"
}
trap exit_trap EXIT
set -e
echo "foo"
false 12345
echo "bar"
The output is
foo
Command [false 12345] exited with code [1]
bar
is never printed because set -e
causes bash to exit the script when a command fails and the false command always fails (by definition). The 12345
passed to false
is just there to show that the arguments to the failed command are captured as well (the false
command ignores any arguments passed to it)
Another way is to use Cairographics-based SVG, PDF and PostScript Graphics Devices.
This way you don't need to setEPS()
cairo_ps("image.eps")
plot(1, 10)
dev.off()
On Mac using brew is a better option as apt-get is not available. Command:
brew install python
In case you have both python2 & python3 installed on machine
python2.7 -m ensurepip --default-pip
simply should solve the issue.
If instead you are missing pip from python 3 then simply change python2.7
to python3
in the command above.
The easiest way would be to package the Vagrant box and then copy (e.g. scp
or rsync
) it over to the other PC, add it and vagrant up
;-)
For detailed steps, check this out =>
Is there any way to clone a vagrant box that is already installed
If you need use Objective-C or you still in love:
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
You can try using the ModernHttpClient Nuget Package: After downloading the package, you can implement it like this:
var handler = new ModernHttpClient.NativeMessageHandler()
{
UseProxy = true,
};
handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
handler.PreAuthenticate = true;
HttpClient client = new HttpClient(handler);
I had the same problem. Wound up just writing a custom highlight and unhighlight function for the validator. Adding this to the validaton options should add the error class to the element and its respective label:
'highlight': function (element, errorClass, validClass) {
if($(element).attr('type') == 'radio'){
$(element.form).find("input[type=radio]").each(function(which){
$(element.form).find("label[for=" + this.id + "]").addClass(errorClass);
$(this).addClass(errorClass);
});
} else {
$(element.form).find("label[for=" + element.id + "]").addClass(errorClass);
$(element).addClass(errorClass);
}
},
'unhighlight': function (element, errorClass, validClass) {
if($(element).attr('type') == 'radio'){
$(element.form).find("input[type=radio]").each(function(which){
$(element.form).find("label[for=" + this.id + "]").removeClass(errorClass);
$(this).removeClass(errorClass);
});
}else {
$(element.form).find("label[for=" + element.id + "]").removeClass(errorClass);
$(element).removeClass(errorClass);
}
},
You can use the semver package to determine if a version satisfies a semantic version requirement. This is not the same as comparing two actual versions, but is a type of comparison.
For example, version 3.6.0+1234 should be the same as 3.6.0.
import semver
semver.match('3.6.0+1234', '==3.6.0')
# True
from packaging import version
version.parse('3.6.0+1234') == version.parse('3.6.0')
# False
from distutils.version import LooseVersion
LooseVersion('3.6.0+1234') == LooseVersion('3.6.0')
# False
I confirm that git and msysgit can coexist on the same computer, as mentioned in "Which GIT version to use cygwin or msysGit or both?".
Git for Windows (msysgit) will run in its own shell (dos with git-cmd.bat
or bash with Git Bash.vbs
)
Update 2016: msysgit is obsolete, and the new Git for Windows now uses msys2
Git on Cygwin, after installing its package, will run in its own cygwin bash shell.
In there, you can do a sudo apt-get install git-core
and start using git on project-sources present either on the WSL container's "native" file-system (see below), or in the hosting Windows's file-system through the /mnt/c/...
, /mnt/d/...
directory hierarchies.
Specifically for the Bash on Windows or WSL (Windows Subsystem for Linux):
DrvFs
emulated file-system may not behave the same as files on the native VolFs
file-system).
- Unfortunately, it cannot invoke back into Windows executables, or
- interact with any native drivers (i.e. so no Graphic card, no USB drives yet).
Try this very simple answer using date_diff(), this is tested.
$date1 = date_create("2017-11-27");
$date2 = date_create("2018-12-29");
$diff=date_diff($date1,$date2);
$months = $diff->format("%m months");
$years = $diff->format("%y years");
$days = $diff->format("%d days");
echo $years .' '.$months.' '.$days;
the output is:
1 years 1 months 2 days
This is the fresh solution I've used :)
I got the same problem, I'm using Anaconda and Jupyter Notebook.
What I did to solve this problem is NOT to install Graphiz.zip from the intenet!
I just did these steps:
conda create -n [env_name]
conda install graphviz
import os os.environ['PATH'] = os.environ['PATH']+';'+os.environ['CONDA_PREFIX']+r"\Library\bin\graphviz"
Finally, The image is appeared, I made a small party for this because it took 3 days from me :(
From man 7 gitrevisions
:
HEAD names the commit on which you based the changes in the working tree. FETCH_HEAD records the branch which you fetched from a remote repository with your last git fetch invocation. ORIG_HEAD is created by commands that move your HEAD in a drastic way, to record the position of the HEAD before their operation, so that you can easily change the tip of the branch back to the state before you ran them. MERGE_HEAD records the commit(s) which you are merging into your branch when you run git merge. CHERRY_PICK_HEAD records the commit which you are cherry-picking when you run git cherry-pick.
var defaults = {_x000D_
_x000D_
"background-color": "#000",_x000D_
color: "#fff",_x000D_
weekdays: [_x000D_
{0: 'sun'},_x000D_
{1: 'mon'},_x000D_
{2: 'tue'},_x000D_
{3: 'wed'},_x000D_
{4: 'thu'},_x000D_
{5: 'fri'},_x000D_
{6: 'sat'}_x000D_
]_x000D_
_x000D_
};_x000D_
_x000D_
console.log(defaults.weekdays[3]);
_x000D_
This is how I implemented Spring MVC Multipart Request with JSON Data.
Based on RESTful service in Spring 4.0.2 Release, HTTP request with the first part as XML or JSON formatted data and the second part as a file can be achieved with @RequestPart. Below is the sample implementation.
Rest service in Controller will have mixed @RequestPart and MultipartFile to serve such Multipart + JSON request.
@RequestMapping(value = "/executesampleservice", method = RequestMethod.POST,
consumes = {"multipart/form-data"})
@ResponseBody
public boolean executeSampleService(
@RequestPart("properties") @Valid ConnectionProperties properties,
@RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file) {
return projectService.executeSampleService(properties, file);
}
Create a FormData object.
Append the file to the FormData object using one of the below steps.
formData.append("file", document.forms[formName].file.files[0]);
formData.append("file", myFile, "myfile.txt");
OR formData.append("file", myBob, "myfile.txt");
Create a blob with the stringified JSON data and append it to the FormData object. This causes the Content-type of the second part in the multipart request to be "application/json" instead of the file type.
Send the request to the server.
Request Details:
Content-Type: undefined
. This causes the browser to set the Content-Type to multipart/form-data and fill the boundary correctly. Manually setting Content-Type to multipart/form-data will fail to fill in the boundary parameter of the request.
formData = new FormData();
formData.append("file", document.forms[formName].file.files[0]);
formData.append('properties', new Blob([JSON.stringify({
"name": "root",
"password": "root"
})], {
type: "application/json"
}));
method: "POST",
headers: {
"Content-Type": undefined
},
data: formData
Accept:application/json, text/plain, */*
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryEBoJzS3HQ4PgE1QB
------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="file"; filename="myfile.txt"
Content-Type: application/txt
------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="properties"; filename="blob"
Content-Type: application/json
------WebKitFormBoundaryvijcWI2ZrZQ8xEBN--
I'm fond of using = {0};
to initialize structures without needing to call memset.
struct something X = {0};
This will initialize all of the members of the struct (or array) to zero (but not any padding bytes - use memset if you need to zero those as well).
But you should be aware there are some issues with this for large, dynamically allocated structures.
let genderS = Array.from(document.getElementsByName("genderS")).find(r => r.checked).value;
For what purpose is this function useful?
One particular usage is counting with a dictionary. Let's assume you want to count the number of occurrences of each element in a given list. The common way to do so is to make a dictionary where keys are elements and values are the number of occurrences.
fruits = ['apple', 'banana', 'peach', 'apple', 'pear']
d = {}
for fruit in fruits:
if fruit not in d:
d[fruit] = 0
d[fruit] += 1
Using the .get()
method, you can make this code more compact and clear:
for fruit in fruits:
d[fruit] = d.get(fruit, 0) + 1
<Button x:Name="mybtnSave" FlowDirection="LeftToRight" HorizontalAlignment="Left" Margin="813,614,0,0" VerticalAlignment="Top" Width="223" Height="53" BorderBrush="#FF2B3830" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontFamily="B Titr" FontSize="15" FontWeight="Bold" BorderThickness="2" TabIndex="107" Click="mybtnSave_Click" >
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="#FF080505" Offset="1"/>
<GradientStop Color="White" Offset="0.536"/>
</LinearGradientBrush>
</Button.Background>
<Button.Effect>
<DropShadowEffect/>
</Button.Effect>
<StackPanel HorizontalAlignment="Stretch" Cursor="Hand" >
<StackPanel.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF3ED82E" Offset="0"/>
<GradientStop Color="#FF3BF728" Offset="1"/>
<GradientStop Color="#FF212720" Offset="0.52"/>
</LinearGradientBrush>
</StackPanel.Background>
<Image HorizontalAlignment="Left" Source="image/Append Or Save 3.png" Height="36" Width="203" />
<TextBlock HorizontalAlignment="Center" Width="145" Height="22" VerticalAlignment="Top" Margin="0,-31,-35,0" Text="Save Com F12" FontFamily="Tahoma" FontSize="14" Padding="0,4,0,0" Foreground="White" />
</StackPanel>
</Button>ente[![enter image description here][1]][1]r image description here
Here is one more option without too much JS hassle: https://github.com/kmahelona/ipython_notebook_goodies
If you're using the resource routes, then in the HTML body of the form, you can use method_field helper like this:
<form>
{{ csrf_field() }}
{{ method_field('PUT') }}
<!-- ... -->
</form>
It will create hidden form input with method type, that is correctly interpereted by Laravel 5.5+.
Since Laravel 5.6 you can use following Blade directives in the templates:
<form>
@method('put')
@csrf
<!-- ... -->
</form>
Hope this might help someone in the future.
See mozilla.org's write-up on how CORS works.
You'll need your server to send back the proper response headers, something like:
Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, PUT, GET, OPTIONS
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization
Bear in mind you can use "*"
for Access-Control-Allow-Origin
that will only work if you're trying to pass Authentication data. In that case, you need to explicitly list the origin domains you want to allow. To allow multiple domains, see this post
The most robust mechanism for listing all resources in the classpath is currently to use this pattern with ClassGraph, because it handles the widest possible array of classpath specification mechanisms, including the new JPMS module system. (I am the author of ClassGraph.)
How to know the name of the JAR file where my main class lives?
URI mainClasspathElementURI;
try (ScanResult scanResult = new ClassGraph().whitelistPackages("x.y.z")
.enableClassInfo().scan()) {
mainClasspathElementURI =
scanResult.getClassInfo("x.y.z.MainClass").getClasspathElementURI();
}
How can I read the contents of a directory in a similar fashion within a JAR file?
List<String> classpathElementResourcePaths;
try (ScanResult scanResult = new ClassGraph().overrideClasspath(mainClasspathElementURI)
.scan()) {
classpathElementResourcePaths = scanResult.getAllResources().getPaths();
}
There are lots of other ways to deal with resources too.
For mysqli you can use :
$db = ADONewConnection('mysqli');
... ...
$db->execute("set names 'utf8'");
Use This code to handle currency format for india. Country code can be changed to handle other country currency.
let amount =350256.95
var formatter = new Intl.NumberFormat('en-IN', {
minimumFractionDigits: 2,
});
// Use it.
formatter.format(amount);
output:
3,50,256.95
Best solution to this is css/html: Make a div to wrap your elements in, if you dont have it already And set it to position fixed and overflow hidden. Optional, set height and width to 100% if you want it to fill the whole screen and nothing but the whole screen
#wrapper{_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
position: fixed;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<p>All</p>_x000D_
<p>Your</p>_x000D_
<p>Elements</p>_x000D_
</div>
_x000D_
Have a look at http://sqlite.org/lang_conflict.html.
You want something like:
insert or replace into Book (ID, Name, TypeID, Level, Seen) values
((select ID from Book where Name = "SearchName"), "SearchName", ...);
Note that any field not in the insert list will be set to NULL if the row already exists in the table. This is why there's a subselect for the ID
column: In the replacement case the statement would set it to NULL and then a fresh ID would be allocated.
This approach can also be used if you want to leave particular field values alone if the row in the replacement case but set the field to NULL in the insert case.
For example, assuming you want to leave Seen
alone:
insert or replace into Book (ID, Name, TypeID, Level, Seen) values (
(select ID from Book where Name = "SearchName"),
"SearchName",
5,
6,
(select Seen from Book where Name = "SearchName"));
I got this error, after all fiddling work I could do — the disk space was full!
Clearing it fixed my issue.
Java Function to bring Linux Command Result!
public String RunLinuxCommand(String cmd) throws IOException {
String linuxCommandResult = "";
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
try {
while ((linuxCommandResult = stdInput.readLine()) != null) {
return linuxCommandResult;
}
while ((linuxCommandResult = stdError.readLine()) != null) {
return "";
}
} catch (Exception e) {
return "";
}
return linuxCommandResult;
}
Json.NET does this...
Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("key1", "value1");
values.Add("key2", "value2");
string json = JsonConvert.SerializeObject(values);
// {
// "key1": "value1",
// "key2": "value2"
// }
More examples: Serializing Collections with Json.NET
To respect fast readers, I start with precise definition first, continue with quick more "plain English" explanation, and then move to examples.
Here is a both concise and precise definition slightly reworded:
A monad (in computer science) is formally a map that:
sends every type
X
of some given programming language to a new typeT(X)
(called the "type ofT
-computations with values inX
");equipped with a rule for composing two functions of the form
f:X->T(Y)
andg:Y->T(Z)
to a functiong°f:X->T(Z)
;in a way that is associative in the evident sense and unital with respect to a given unit function called
pure_X:X->T(X)
, to be thought of as taking a value to the pure computation that simply returns that value.
So in simple words, a monad is a rule to pass from any type X
to another type T(X)
, and a rule to pass from two functions f:X->T(Y)
and g:Y->T(Z)
(that you would like to compose but can't) to a new function h:X->T(Z)
. Which, however, is not the composition in strict mathematical sense. We are basically "bending" function's composition or re-defining how functions are composed.
Plus, we require the monad's rule of composing to satisfy the "obvious" mathematical axioms:
f
with g
and then with h
(from outside) should be the same as composing g
with h
and then with f
(from inside).f
with the identity function on either side should yield f
.Again, in simple words, we can't just go crazy re-defining our function composition as we like:
f(g(h(k(x)))
, and not to worry about specifying the order composing function pairs. As the monad rule only prescribes how to compose a pair of functions, without that axiom, we would need to know which pair is composed first and so on. (Note that is different from the commutativity property that f
composed with g
were the same as g
composed with f
, which is not required). So again in brief: A monad is the rule of type extension and composing functions satisfying the two axioms -- associativity and unital property.
In practical terms, you want the monad to be implemented for you by the language, compiler or framework that would take care of composing functions for you. So you can focus on writing your function's logic rather than worrying how their execution is implemented.
That is essentially it, in a nutshell.
Being professional mathematician, I prefer to avoid calling h
the "composition" of f
and g
. Because mathematically, it isn't. Calling it the "composition" incorrectly presumes that h
is the true mathematical composition, which it isn't. It is not even uniquely determined by f
and g
. Instead, it is the result of our monad's new "rule of composing" the functions. Which can be totally different from the actual mathematical composition even if the latter exists!
To make it less dry, let me try to illustrate it by example that I am annotating with small sections, so you can skip right to the point.
Suppose we want to compose two functions:
f: x -> 1 / x
g: y -> 2 * y
But f(0)
is not defined, so an exception e
is thrown. Then how can you define the compositional value g(f(0))
? Throw an exception again, of course! Maybe the same e
. Maybe a new updated exception e1
.
What precisely happens here? First, we need new exception value(s) (different or same). You can call them nothing
or null
or whatever but the essence remains the same -- they should be new values, e.g. it should not be a number
in our example here. I prefer not to call them null
to avoid confusion with how null
can be implemented in any specific language. Equally I prefer to avoid nothing
because it is often associated with null
, which, in principle, is what null
should do, however, that principle often gets bended for whatever practical reasons.
This is a trivial matter for any experienced programmer but I'd like to drop few words just to extinguish any worm of confusion:
Exception is an object encapsulating information about how the invalid result of execution occurred.
This can range from throwing away any details and returning a single global value (like NaN
or null
) or generating a long log list or what exactly happened, send it to a database and replicating all over the distributed data storage layer ;)
The important difference between these two extreme examples of exception is that in the first case there are no side-effects. In the second there are. Which brings us to the (thousand-dollar) question:
Shorter answer: Yes, but only when they don't lead to side-effects.
Longer answer. To be pure, your function's output must be uniquely determined by its input. So we amend our function f
by sending 0
to the new abstract value e
that we call exception. We make sure that value e
contains no outside information that is not uniquely determined by our input, which is x
. So here is an example of exception without side-effect:
e = {
type: error,
message: 'I got error trying to divide 1 by 0'
}
And here is one with side-effect:
e = {
type: error,
message: 'Our committee to decide what is 1/0 is currently away'
}
Actually, it only has side-effects if that message can possibly change in the future. But if it is guaranteed to never change, that value becomes uniquely predictable, and so there is no side-effect.
To make it even sillier. A function returning 42
ever is clearly pure. But if someone crazy decides to make 42
a variable that value might change, the very same function stops being pure under the new conditions.
Note that I am using the object literal notation for simplicity to demonstrate the essence. Unfortunately things are messed-up in languages like JavaScript, where error
is not a type that behaves the way we want here with respect to function composition, whereas actual types like null
or NaN
do not behave this way but rather go through the some artificial and not always intuitive type conversions.
As we want to vary the message inside our exception, we are really declaring a new type E
for the whole exception object and then
That is what the maybe number
does, apart from its confusing name, which is to be either of type number
or of the new exception type E
, so it is really the union number | E
of number
and E
. In particular, it depends on how we want to construct E
, which is neither suggested nor reflected in the name maybe number
.
It is the mathematical operation taking functions
f: X -> Y
and g: Y -> Z
and constructing
their composition as function h: X -> Z
satisfying h(x) = g(f(x))
.
The problem with this definition occurs when the result f(x)
is not allowed as argument of g
.
In mathematics those functions cannot be composed without extra work.
The strictly mathematical solution for our above example of f
and g
is to remove 0
from the set of definition of f
. With that new set of definition (new more restrictive type of x
), f
becomes composable with g
.
However, it is not very practical in programming to restrict the set of definition of f
like that. Instead, exceptions can be used.
Or as another approach, artificial values are created like NaN
, undefined
, null
, Infinity
etc. So you evaluate 1/0
to Infinity
and 1/-0
to -Infinity
. And then force the new value back into your expression instead of throwing exception. Leading to results you may or may not find predictable:
1/0 // => Infinity
parseInt(Infinity) // => NaN
NaN < 0 // => false
false + 1 // => 1
And we are back to regular numbers ready to move on ;)
JavaScript allows us to keep executing numerical expressions at any costs without throwing errors as in the above example. That means, it also allows to compose functions. Which is exactly what monad is about - it is a rule to compose functions satisfying the axioms as defined at the beginning of this answer.
But is the rule of composing function, arising from JavaScript's implementation for dealing with numerical errors, a monad?
To answer this question, all you need is to check the axioms (left as exercise as not part of the question here;).
Indeed, a more useful monad would instead be the rule prescribing
that if f
throws exception for some x
, so does its composition with any g
. Plus make the exception E
globally unique with only one possible value ever (terminal object in category theory). Now the two axioms are instantly checkable and we get a very useful monad. And the result is what is well-known as the maybe monad.
From jquery prospective - it's just adding load
/onload
event to window and document.
Check this out:
You can combine tuple and XOR swaps: x, y = x ^ x ^ y, x ^ y ^ y
x, y = 10, 20
print('Before swapping: x = %s, y = %s '%(x,y))
x, y = x ^ x ^ y, x ^ y ^ y
print('After swapping: x = %s, y = %s '%(x,y))
or
x, y = 10, 20
print('Before swapping: x = %s, y = %s '%(x,y))
print('After swapping: x = %s, y = %s '%(x ^ x ^ y, x ^ y ^ y))
Using lambda:
x, y = 10, 20
print('Before swapping: x = %s, y = %s' % (x, y))
swapper = lambda x, y : ((x ^ x ^ y), (x ^ y ^ y))
print('After swapping: x = %s, y = %s ' % swapper(x, y))
Output:
Before swapping: x = 10 , y = 20
After swapping: x = 20 , y = 10
if files are not moving this could be due to several reasons
> find * -type d -print0 | xargs -0 chmod 0755 # for directories find * > -type f -print0 | xargs -0 chmod 0666 # for files
chown -R admin:admin public_html # will restore permission to admin for folder and files within it chown admin:admin public_html # will restore permission to admin for folder only will skip files
copy
function instead of move_uploaded_file
Below is the program to execute the rest api in python-
import requests
url = 'https://url'
data = '{ "platform": { "login": { "userName": "name", "password": "pwd" } } }'
response = requests.post(url, data=data,headers={"Content-Type": "application/json"})
print(response)
sid=response.json()['platform']['login']['sessionId'] //to extract the detail from response
print(response.text)
print(sid)
Iterative development implies revisiting usual waterfall model steps over the course of product lifetime. The stages can even overlap, i.e. while doing end-to-end testing you could already start preparing new requirements.
Incremental development means you roadmap your features and implement them incrementally.
Agile aims at creating "potentially shippable product" after every sprint. How you achieve it is a different story. Agile tries to employ "best" techniques from various fields (e.g. extreme programming). Agile does not exclude running neither incremental nor iterative development.
Setting my RequestOperationManager
Response Serializer to HTTPResponseSerializer
fixed the issue.
Objective-C
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
Swift
manager.responseSerializer = AFHTTPResponseSerializer()
Making this change means I don't need to add acceptableContentTypes
to every request I make.
Hi you can download using boto3. In python
import boto3
from boto3.dynamodb.conditions import Key, Attr
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Table')
response = table.scan()
items = response['Items']
while 'LastEvaluatedKey' in response:
print(response['LastEvaluatedKey'])
response = table.scan(ExclusiveStartKey=response['LastEvaluatedKey'])
items.extend(response['Items'])
MS-DOS Editor (or just edit
) is a 16-bit text editor that is still included with 32-bit versions of Windows XP, Vista, 7, 8 and 8.1. It can edit files upto 65,279 lines long and has mouse support. Being an 16-bit DOS editor, it cannot run directly on 64-bit versions of Windows. It can be launched by typing edit
at the command prompt.
The simplest ways for me are these ones:
array = [1, 2, 2, 3]
Array#to_set
array.to_set.to_a
# [1, 2, 3]
Array#uniq
array.uniq
# [1, 2, 3]
You can set a JavaScript variable in your WepPage that gets set once it's been loaded. You could put it anywhere, but if you're using jQuery, $(document).onReady
isn't a bad place to start. If not, then you can put it in a <script>
tag at the bottom of the page.
The advantage of this method as opposed to checking for element visibility is that you know the exact state of the page after the wait
statement executes.
... All my page content ...
<script> window.TestReady = true; </script></body></html>
And in your test (C# example):
// The timespan determines how long to wait for any 'condition' to return a value
// If it is exceeded an exception is thrown.
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5.0));
// Set the 'condition' as an anonymous function returning a boolean
wait.Until<Boolean>(delegate(IWebDriver d)
{
// Check if our global variable is initialized by running a little JS
return (Boolean)((IJavaScriptExecutor)d).ExecuteScript("return typeof(window.TestReady) !== 'undefined' && window.TestReady === true");
});
Try:
"TimeStamp":{$toDecimal: { $toDate:"$Datum"}}
Hello you need to open the index.php from the wamp server and change $suppress_localhost = false; from $suppress_localhost = true; then your wamp will working fine
The unwanted folders can be also be deleted by the following way:
zip -d filename.zip "__MACOSX*"
Works best for me
A char
represents a character in Java (*). It is 2 bytes large (at least that's what the valid value range suggests).
That doesn't necessarily mean that every representation of a character is 2 bytes long. In fact many encodings only reserve 1 byte for every character (or use 1 byte for the most common characters).
When you call the String(byte[])
constructor you ask Java to convert the byte[]
to a String
using the platform default encoding. Since the platform default encoding is usually a 1-byte encoding such as ISO-8859-1 or a variable-length encoding such as UTF-8, it can easily convert that 1 byte to a single character.
If you run that code on a platform that uses UTF-16 (or UTF-32 or UCS-2 or UCS-4 or ...) as the platform default encoding, then you will not get a valid result (you'll get a String
containing the Unicode Replacement Character instead).
That's one of the reasons why you should not depend on the platform default encoding: when converting between byte[]
and char[]
/String
or between InputStream
and Reader
or between OutputStream
and Writer
, you should always specify which encoding you want to use. If you don't, then your code will be platform-dependent.
(*) that's not entirely true: a char
represents a UTF-16 codepoint. Either one or two UTF-16 codepoints represent a Unicode codepoint. A Unicode codepoint usually represents a character, but sometimes multiple Unicode codepoints are used to make up a single character. But the approximation above is close enough to discuss the topic at hand.
public static List<HtmlNode> GetTagsWithClass(string html,List<string> @class)
{
// LoadHtml(html);
var result = htmlDocument.DocumentNode.Descendants()
.Where(x =>x.Attributes.Contains("class") && @class.Contains(x.Attributes["class"].Value)).ToList();
return result;
}
Yes. Youtube API is the best resource for this.
There are 3 way to embed a video:
<iframe>
tagsDEPRECATED
I think you are looking for the second one of them:
The HTML and JavaScript code below shows a simple example that inserts a YouTube player into the page element that has an id value of ytplayer. The onYouTubePlayerAPIReady() function specified here is called automatically when the IFrame Player API code has loaded. This code does not define any player parameters and also does not define other event handlers.
<div id="ytplayer"></div>
<script>
// Load the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Replace the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('ytplayer', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE'
});
}
</script>
Here are some instructions where you may take a look when starting using the API.
An embed example without using iframe
is to use <object>
tag:
<object width="640" height="360">
<param name="movie" value="http://www.youtube.com/embed/yt-video-id?html5=1&rel=0&hl=en_US&version=3"/
<param name="allowFullScreen" value="true"/>
<param name="allowscriptaccess" value="always"/>
<embed width="640" height="360" src="http://www.youtube.com/embed/yt-video-id?html5=1&rel=0&hl=en_US&version=3" class="youtube-player" type="text/html" allowscriptaccess="always" allowfullscreen="true"/>
</object>
(replace yt-video-id
with your video id)
Actually i am getting return value from a another sp into @temp and then it @temp =1 then i want to inc the count of @SelectoneCount by 1 and so on. Please let me know what is the correct syntax.
What's wrong with:
IF @Temp = 1 --Or @Temp = 2 also?
BEGIN
SET @SelectoneCount = @SelectoneCount + 1
END
(Although this does reek of being procedural code - not usually the best way to use SQL)
<?php
$php_multi_array = array("lang"=>"PHP", "type"=>array("c_type"=>"MULTI", "p_type"=>"ARRAY"));
//Iterate through an array declared above
foreach($php_multi_array as $key => $value)
{
if (!is_array($value))
{
echo $key ." => ". $value ."\r\n" ;
}
else
{
echo $key ." => array( \r\n";
foreach ($value as $key2 => $value2)
{
echo "\t". $key2 ." => ". $value2 ."\r\n";
}
echo ")";
}
}
?>
OUTPUT:
lang => PHP
type => array(
c_type => MULTI
p_type => ARRAY
)
Go ahead and add [STAThread] to the main entry of your application, this indicates the COM threading model is single-threaded apartment (STA)
example:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new WebBrowser());
}
}
Alternate solution
Create a column that will store the month:
data['month'] = data['date'].dt.month
Create a column that will store the year:
data['year'] = data['date'].dt.year
Fast C# solution using pre-calculated table of Byte bit counts with branching on input size.
public static class BitCount
{
public static uint GetSetBitsCount(uint n)
{
var counts = BYTE_BIT_COUNTS;
return n <= 0xff ? counts[n]
: n <= 0xffff ? counts[n & 0xff] + counts[n >> 8]
: n <= 0xffffff ? counts[n & 0xff] + counts[(n >> 8) & 0xff] + counts[(n >> 16) & 0xff]
: counts[n & 0xff] + counts[(n >> 8) & 0xff] + counts[(n >> 16) & 0xff] + counts[(n >> 24) & 0xff];
}
public static readonly uint[] BYTE_BIT_COUNTS =
{
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8
};
}
You need to enclose that in <%! %> as follows:
<%!
public String getQuarter(int i){
String quarter;
switch(i){
case 1: quarter = "Winter";
break;
case 2: quarter = "Spring";
break;
case 3: quarter = "Summer I";
break;
case 4: quarter = "Summer II";
break;
case 5: quarter = "Fall";
break;
default: quarter = "ERROR";
}
return quarter;
}
%>
You can then invoke the function within scriptlets or expressions:
<%
out.print(getQuarter(4));
%>
or
<%= getQuarter(17) %>
To escape you could just use this from Java 1.5:
Pattern.quote("$test");
You will match exacty the word $test
Or Check https://dev.mysql.com/doc/workbench/en/wb-admin-export-import-management.html
I used the html tag to change a single item's text colour when the menu item is inflated. Hope it would be helpful.
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
menu.findItem(R.id.main_settings).setTitle(Html.fromHtml("<font color='#ff3824'>Settings</font>"));
return true;
}
I think you can use the TimeZoneInfo....to convert the datetime....
static void Main(string[] args)
{
long time = 1310522400000;
DateTime dt_1970 = new DateTime(1970, 1, 1);
long tricks_1970 = dt_1970.Ticks;
long time_tricks = tricks_1970 + time * 10000;
DateTime dt = new DateTime(time_tricks);
Console.WriteLine(dt.ToShortDateString()); // result : 7/13
dt = TimeZoneInfo.ConvertTimeToUtc(dt);
Console.WriteLine(dt.ToShortDateString()); // result : 7/12
Console.Read();
}
It requires lots of things in place to get location updates in android, requires lots of bolierplate code.
You need to take care of
I have created Android-EasyLocation (small android library) which will take care all this stuff and you can focus on business logic.
All you need is extend EasyLocationActivity and this
requestSingleLocationFix(easyLocationRequest);
or
requestLocationUpdates(easyLocationRequest);
Checkout sample app and steps needed here at https://github.com/akhgupta/Android-EasyLocation
On Windows, you can use Mac on a virtual machine (this probably also works on Linux but I haven't tested). A virtual machine is basically a program that you run on your computer that allows you to run one OS in a window inside another one. Make sure you have at least 60GB free space on your hard drive. The virtual hard drive that you will download takes up 10GB initially but when you've installed all the necessary programs for developing iOS apps its size can easily increase to 50GB (I recommend leaving a few GBs margin just in case).
Here are some detailed steps for how install a Mac virtual machine on Windows:
Install VirtualBox.
You have to enable virtualization in the BIOS. To open the BIOS on Windows 10, you need to start by holding down the Shift key while pressing the Restart button in the start menu. Then you will get a blue screen with some options. Choose "Troubleshoot", then "Advanced options", then "UEFI Firmware Settings", then "Restart". Then your computer will restart and open the BIOS directly. On older versions of Windows, shut down the computer normally, hold the F2 key down, start your computer again and don't release F2 until you're in the BIOS. On some computers you may have to hold down another key than F2.
Now that you're in the BIOS, you need to enable virtualization. Which setting you're supposed to change depends on which computer you're using. This may vary even between two computers with the same version of Windows. On my computer, you need to set Intel Virtual Technology
in the Configuration
tab to Enabled
. On other computers it may be in for example Security -> Virtualization
or in Advanced -> CPU Setup
. If you can't find any of these options, search Google for enable virtualization (the kind of computer you have)
. Don't change anything in the BIOS just like that at random because otherwise it could cause problems on your computer. When you've enabled virtualization, save the changes and exit the BIOS. This is usually done in the Exit
tab.
Download this file (I have no association with the person who uploaded it, but I've used it myself so I'm sure there are no viruses). If the link gets broken, post a comment to let me know and I will try to upload the file somewhere else. The password to open the 7Z file is stackoverflow.com
. This 7Z file contains a VMDK file which will act as the hard drive for the Mac virtual machine. Extract that VMDK file. If disk space is an issue for you, once you've extracted the VMDK file, you can delete the 7Z file and therefore save 7GB.
Open VirtualBox that you installed in step 1. In the toolbar, press the New button. Then choose a name for your virtual machine (the name is unimportant, I called it "Mac"). In "Type", select "Mac OS X" and in "Version" select "macOS 10.13 High Sierra (64 bit)" (the Mac version you will install on the virtual machine is actually Catalina, but VirtualBox doesn't have that option yet and it works just fine if VirtualBox thinks it's High Sierra).
It's also a good idea (though not required) to move the VMDK file you extracted in step 4 to the folder listed under "Machine Folder" (in the screenshot above that would be C:\Users\myname\VirtualBox VMs
).
Select the amount of memory that your virtual machine can use. Try to balance the amount because too little memory will result in the virtual machine having low performance and a too much memory will result making your host system (Windows) run out of memory which will cause the virtual machine and/or other programs that you're running on Windows to crash. On a computer with 4GB available memory, 2GB was a good amount. Don't worry if you select a bad amount, you will be able to change it whenever you want (except when the virtual machine is running).
In the Hard disk step, choose "Use an existing virtual hard disk file" and click on the little folder icon to the right of the drop list. That will open a new window. In that new window, click on the "Add" button on the top left, which will open a browse window. Select the VMDK file that you downloaded and extracted in step 4, then click "Choose".
When you're done with this, click "Create".
Select the virtual machine in the list on the left of the window and click on the Settings button in the toolbar. In System -> Processor, select 2 CPUs; and in Network -> Attached to, select Bridged Adapter. If you realize later that you selected an amount of memory in step 6 that causes problems, you can change it in System -> Motherboard. When you're done changing the settings, click OK.
Open the command prompt (C:\Windows\System32\cmd.exe
). Run the following commands in there, replacing "Your VM Name"
with whatever you called your virtual machine in step 5 (for example "Mac"
) (keep the quotation marks):
cd "C:\Program Files\Oracle\VirtualBox\"
VBoxManage.exe modifyvm "Your VM Name" --cpuidset 00000001 000106e5 00100800 0098e3fd bfebfbff
VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/efi/0/Config/DmiSystemProduct" "iMac11,3"
VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/efi/0/Config/DmiSystemVersion" "1.0"
VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/efi/0/Config/DmiBoardProduct" "Iloveapple"
VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/smc/0/Config/DeviceKey" "ourhardworkbythesewordsguardedpleasedontsteal(c)AppleComputerInc"
VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/smc/0/Config/GetKeyFromRealSMC" 1
VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/efi/0/Config/DmiSystemSerial" C02L280HFMR7
Now everything is ready for you to use the virtual machine. In VirtualBox, click on the Start button and follow the installation instructions for Mac. Once you've installed Mac on the virtual machine, you can develop your iOS app just like if you had a real Mac.
Remark: If you want to save space on your hard disk, you can compress the VMDK file that you extracted in step 4 and used in step 7. To do this, right click on it, select Properties, click on the Advanced... button on the bottom right, and check the checkbox "Compress contents to save disk space". This will make this very large file take less disk space without making anything work less well. I did it and it reduced the disk size of the VMDK file from 50GB to 40GB without losing any data.
If you are using >= .NET 4 then you can use Tuple
Class:
// declaration
var list = new List<Tuple<string, List<object>>>();
// to add an item to the list
var item = Tuple<string, List<object>>("key", new List<object>);
list.Add(item);
// to iterate
foreach(var i in list)
{
Console.WriteLine(i.Item1.ToString());
}
You can use a fantastic library name Videojs. You will find more useful informations here. But with quick start you can do something like this:
<link href="//vjs.zencdn.net/5.11/video-js.min.css" rel="stylesheet">
<script src="//vjs.zencdn.net/5.11/video.min.js"></script>
<video
id="Video"
class="video-js vjs-default-skin vjs-big-play-centered"
controls
preload="none"
width="auto"
height="auto"
poster="poster.jpg"
data-setup='{"techOrder": ["flash", "html5", "other supported tech"], "nativeControlsForTouch": true, "controlBar": { "muteToggle": false, "volumeControl": false, "timeDivider": false, "durationDisplay": false, "progressControl": false } }'
>
<source src="rtmp://{domain_server}/{publisher}" type='rtmp/mp4'/>
</video>
<script>
var player = videojs('Video');
player.play();
</script>
The agg
function will do this for you. Pass the columns and function as a dict with column, output:
df.groupby(['Country', 'Item_Code']).agg({'Y1961': np.sum, 'Y1962': [np.sum, np.mean]}) # Added example for two output columns from a single input column
This will display only the group by columns, and the specified aggregate columns. In this example I included two agg functions applied to 'Y1962'.
To get exactly what you hoped to see, included the other columns in the group by, and apply sums to the Y variables in the frame:
df.groupby(['Code', 'Country', 'Item_Code', 'Item', 'Ele_Code', 'Unit']).agg({'Y1961': np.sum, 'Y1962': np.sum, 'Y1963': np.sum})
If you have two buttons and have the same id call to your button click events like this:
Button btn1;
Button btn2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1= (Button)findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,target.class);
startActivity(intent);
}
});
btn2=(Button) findViewById(R.id.button1);//Have same id call previous button---> button1
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
When you clicked button1
, button2
will work and you cannot open your second activity.
IE has its own way: A css property, -ms-content-zooming. Setting it to none on the body or something should disable it.
http://msdn.microsoft.com/en-us/library/ie/hh771891(v=vs.85).aspx
I've discovered that if your computer goes to sleep then the docker container goes out of sync.
https://forums.docker.com/t/time-in-container-is-out-of-sync/16566
I have made a post about it here Certificate always expires 5 days ago in Docker
Try this
void Function()
{
while (condition)
{
await Task.Delay(1);
}
}
This will make the program wait until the condition is not true. You can just invert it by adding a "!" infront of the condition so that it will wait until the condition is true.
You cannot define a variable of an incomplete type. You need to bring the whole definition of Cat
into scope before you can create the local variable in main
. I recommend that you move the definition of the type Cat
to a header and include it from the translation unit that has main
.
To return to the latest version:
git checkout <branch-name>
For example, git checkout master
or git checkout dev
@Presto Thanks! Yours worked perfectly for me, but I came up with a simpler version to save changing everything around.
Add a <span>
tag around the desired link text, specifying class within. (e.g. home tag)
<nav id="top-menu">
<ul>
<li> <a href="home.html"><span class="currentLink">Home</span></a> </li>
<li> <a href="about.html">About</a> </li>
<li> <a href="cv.html">CV</a> </li>
<li> <a href="photos.html">Photos</a> </li>
<li> <a href="archive.html">Archive</a> </li>
<li> <a href="contact.html">Contact</a></li>
</ul>
</nav>
Then edit your CSS accordingly:
.currentLink {
color:#baada7;
}
sp_executesql
is more likely to promote query plan reuse. When using sp_executesql
, parameters are explicitly identified in the calling signature. This excellent article descibes this process.
The oft cited reference for many aspects of dynamic sql is Erland Sommarskog's must read: "The Curse and Blessings of Dynamic SQL".
If you're using sqlplus in a shell, like bash you can run the shell's clear command from sqlplus:
SQL> host clear
you can abbreviate of course:
SQL> ho clear
Although Reed Copsey and Marc Gravell already described about IQueryable
(and also IEnumerable
) enough,mI want to add little more here by providing a small example on IQueryable
and IEnumerable
as many users asked for it
Example: I have created two table in database
CREATE TABLE [dbo].[Employee]([PersonId] [int] NOT NULL PRIMARY KEY,[Gender] [nchar](1) NOT NULL)
CREATE TABLE [dbo].[Person]([PersonId] [int] NOT NULL PRIMARY KEY,[FirstName] [nvarchar](50) NOT NULL,[LastName] [nvarchar](50) NOT NULL)
The Primary key(PersonId
) of table Employee
is also a forgein key(personid
) of table Person
Next i added ado.net entity model in my application and create below service class on that
public class SomeServiceClass
{
public IQueryable<Employee> GetEmployeeAndPersonDetailIQueryable(IEnumerable<int> employeesToCollect)
{
DemoIQueryableEntities db = new DemoIQueryableEntities();
var allDetails = from Employee e in db.Employees
join Person p in db.People on e.PersonId equals p.PersonId
where employeesToCollect.Contains(e.PersonId)
select e;
return allDetails;
}
public IEnumerable<Employee> GetEmployeeAndPersonDetailIEnumerable(IEnumerable<int> employeesToCollect)
{
DemoIQueryableEntities db = new DemoIQueryableEntities();
var allDetails = from Employee e in db.Employees
join Person p in db.People on e.PersonId equals p.PersonId
where employeesToCollect.Contains(e.PersonId)
select e;
return allDetails;
}
}
they contains same linq. It called in program.cs
as defined below
class Program
{
static void Main(string[] args)
{
SomeServiceClass s= new SomeServiceClass();
var employeesToCollect= new []{0,1,2,3};
//IQueryable execution part
var IQueryableList = s.GetEmployeeAndPersonDetailIQueryable(employeesToCollect).Where(i => i.Gender=="M");
foreach (var emp in IQueryableList)
{
System.Console.WriteLine("ID:{0}, EName:{1},Gender:{2}", emp.PersonId, emp.Person.FirstName, emp.Gender);
}
System.Console.WriteLine("IQueryable contain {0} row in result set", IQueryableList.Count());
//IEnumerable execution part
var IEnumerableList = s.GetEmployeeAndPersonDetailIEnumerable(employeesToCollect).Where(i => i.Gender == "M");
foreach (var emp in IEnumerableList)
{
System.Console.WriteLine("ID:{0}, EName:{1},Gender:{2}", emp.PersonId, emp.Person.FirstName, emp.Gender);
}
System.Console.WriteLine("IEnumerable contain {0} row in result set", IEnumerableList.Count());
Console.ReadKey();
}
}
The output is same for both obviously
ID:1, EName:Ken,Gender:M
ID:3, EName:Roberto,Gender:M
IQueryable contain 2 row in result set
ID:1, EName:Ken,Gender:M
ID:3, EName:Roberto,Gender:M
IEnumerable contain 2 row in result set
So the question is what/where is the difference? It does not seem to have any difference right? Really!!
Let's have a look on sql queries generated and executed by entity framwork 5 during these period
IQueryable execution part
--IQueryableQuery1
SELECT
[Extent1].[PersonId] AS [PersonId],
[Extent1].[Gender] AS [Gender]
FROM [dbo].[Employee] AS [Extent1]
WHERE ([Extent1].[PersonId] IN (0,1,2,3)) AND (N'M' = [Extent1].[Gender])
--IQueryableQuery2
SELECT
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
COUNT(1) AS [A1]
FROM [dbo].[Employee] AS [Extent1]
WHERE ([Extent1].[PersonId] IN (0,1,2,3)) AND (N'M' = [Extent1].[Gender])
) AS [GroupBy1]
IEnumerable execution part
--IEnumerableQuery1
SELECT
[Extent1].[PersonId] AS [PersonId],
[Extent1].[Gender] AS [Gender]
FROM [dbo].[Employee] AS [Extent1]
WHERE [Extent1].[PersonId] IN (0,1,2,3)
--IEnumerableQuery2
SELECT
[Extent1].[PersonId] AS [PersonId],
[Extent1].[Gender] AS [Gender]
FROM [dbo].[Employee] AS [Extent1]
WHERE [Extent1].[PersonId] IN (0,1,2,3)
Common script for both execution part
/* these two query will execute for both IQueryable or IEnumerable to get details from Person table
Ignore these two queries here because it has nothing to do with IQueryable vs IEnumerable
--ICommonQuery1
exec sp_executesql N'SELECT
[Extent1].[PersonId] AS [PersonId],
[Extent1].[FirstName] AS [FirstName],
[Extent1].[LastName] AS [LastName]
FROM [dbo].[Person] AS [Extent1]
WHERE [Extent1].[PersonId] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=1
--ICommonQuery2
exec sp_executesql N'SELECT
[Extent1].[PersonId] AS [PersonId],
[Extent1].[FirstName] AS [FirstName],
[Extent1].[LastName] AS [LastName]
FROM [dbo].[Person] AS [Extent1]
WHERE [Extent1].[PersonId] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=3
*/
So you have few questions now, let me guess those and try to answer them
Why are different scripts generated for same result?
Lets find out some points here,
all queries has one common part
WHERE [Extent1].[PersonId] IN (0,1,2,3)
why? Because both function IQueryable<Employee> GetEmployeeAndPersonDetailIQueryable
and
IEnumerable<Employee> GetEmployeeAndPersonDetailIEnumerable
of SomeServiceClass
contains one common line in linq queries
where employeesToCollect.Contains(e.PersonId)
Than why is the
AND (N'M' = [Extent1].[Gender])
part is missing in IEnumerable
execution part, while in both function calling we used Where(i => i.Gender == "M") in
program.cs`
Now we are in the point where difference came between
IQueryable
andIEnumerable
What entity framwork does when an IQueryable
method called, it tooks linq statement written inside the method and try to find out if more linq expressions are defined on the resultset, it then gathers all linq queries defined until the result need to fetch and constructs more appropriate sql query to execute.
It provide a lots of benefits like,
like here in example sql server returned to application only two rows after IQueryable execution` but returned THREE rows for IEnumerable query why?
In case of IEnumerable
method, entity framework took linq statement written inside the method and constructs sql query when result need to fetch. it does not include rest linq part to constructs the sql query. Like here no filtering is done in sql server on column gender
.
But the outputs are same? Because 'IEnumerable filters the result further in application level after retrieving result from sql server
SO, what should someone choose?
I personally prefer to define function result as IQueryable<T>
because there are lots of benefit it has over IEnumerable
like, you could join two or more IQueryable functions, which generate more specific script to sql server.
Here in example you can see an IQueryable Query(IQueryableQuery2)
generates a more specific script than IEnumerable query(IEnumerableQuery2)
which is much more acceptable in my point of view.
.service-small option {
font-size: 14px;
padding: 5px;
background: #5c5c5c;
}
I think it because you used .styled-select in start of the class code.
you can do this in different ways:
see here for more details on the second case:
http://msdn.microsoft.com/en-us/library/ff647786.aspx#scalenetchapt10_topic14
and here for details on the last case:
The problem I came across while using Fabian's answer, is implementing it in an MVC view because of the Razor @
symbol. You have to include an additional @
symbol to escape it, like so: @@
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\@@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
I didn't see it elsewhere on this page, so I thought it might be helpful.
Here's a link from Microsoft describing it's usage.
I just tested the code above and got the following js:
function validateEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
Which is doing exactly what it's supposed to do.
Current route properties are present in this.$route
, this.$router
is the instance of router object which gives the configuration of the router. You can get the current route query using this.$route.query
This is an alternate solution/fix... In FF3, You can retrieve file's full path in a textbox instead of file browse box. And that too... By drag/dropping the file!
You can drag drop your file into a text box in your html page. and it will display the file's complete path. This data can transferred to your server easily or manipulate them.
All you have to do is to use the extension DragDropUpload
http://www.teslacore.it/wiki/index.php?title=DragDropUpload
This extension will helps you in drag dropping files into your File Browse (Input file) box. But still you wont able to get the file full path, If you try to retrieve.
So, I tweaked this extension a little. In the way I can drag drop a file on to any "Text Input" box and get the file full path. And thus I can able to get the file full path in FF3 Firefox 3.
Just in case if you have a loop or a json string that need to insert in the database. Try to replace the string with a single quote . here is my solution. example if you have a string that contain's a single quote.
String mystring = "Sample's";
String myfinalstring = mystring.replace("'","''");
String query = "INSERT INTO "+table name+" ("+field1+") values ('"+myfinalstring+"')";
this works for me in c# and java
I used this and it worked. https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-width
html {
scrollbar-width: none;
}
Note: User Agents must apply any scrollbar-width value set on the root element to the viewport.