bool is a primitive type, meaning that the value (true/false in this case) is stored directly in the variable. Boolean is an object. A variable of type Boolean stores a reference to a Boolean object. The only real difference is storage. An object will always take up more memory than a primitive type, but in reality, changing all your Boolean values to bool isn't going to have any noticeable impact on memory usage.
I was wrong; that's how it works in java with boolean and Boolean. In C#, bool and Boolean are both reference types. Both of them store their value directly in the variable, both of them cannot be null, and both of them require a "convertTO" method to store their values in another type (such as int). It only matters which one you use if you need to call a static function defined within the Boolean class.
A stateless system can be seen as a box [black? ;)] where at any point in time the value of the output(s) depends only on the value of the input(s) [after a certain processing time]
A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.
From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue [as an example think of a reentrant function] A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.
Here is the way I look at COALESCE...and hopefully it makes sense...
In a simplistic form….
Coalesce(FieldName, 'Empty')
So this translates to…If "FieldName" is NULL, populate the field value with the word "EMPTY".
Now for mutliple values...
Coalesce(FieldName1, FieldName2, Value2, Value3)
If the value in Fieldname1 is null, fill it with the value in Fieldname2, if FieldName2 is NULL, fill it with Value2, etc.
This piece of test code for the AdventureWorks2012 sample database works perfectly & gives a good visual explanation of how COALESCE works:
SELECT Name, Class, Color, ProductNumber,
COALESCE(Class, Color, ProductNumber) AS FirstNotNull
FROM Production.Product
I believe you should escape the dot. Try:
String filename = "D:/some folder/001.docx";
String extensionRemoved = filename.split("\\.")[0];
Otherwise dot is interpreted as any character in regular expressions.
You can use as many colors and images as you desire.
Please note that the priority with which the background images are rendered is FILO, the first specified image is on the top layer, the last specified image is on the bottom layer (see the snippet).
#composition {_x000D_
width: 400px;_x000D_
height: 200px;_x000D_
background-image:_x000D_
linear-gradient(to right, #FF0000, #FF0000), /* gradient 1 as solid color */_x000D_
linear-gradient(to right, #00FF00, #00FF00), /* gradient 2 as solid color */_x000D_
linear-gradient(to right, #0000FF, #0000FF), /* gradient 3 as solid color */_x000D_
url('http://lorempixel.com/400/200/'); /* image */_x000D_
background-repeat: no-repeat; /* same as no-repeat, no-repeat, no-repeat */_x000D_
background-position:_x000D_
0 0, /* gradient 1 */_x000D_
20px 0, /* gradient 2 */_x000D_
40px 0, /* gradient 3 */_x000D_
0 0; /* image position */_x000D_
background-size:_x000D_
30px 30px,_x000D_
30px 30px,_x000D_
30px 30px,_x000D_
100% 100%;_x000D_
}
_x000D_
<div id="composition">_x000D_
</div>
_x000D_
You need to set the flags after the project
command in your CMakeLists.txt.
Also, if you're calling include(${QT_USE_FILE})
or add_definitions(${QT_DEFINITIONS})
, you should include these set
commands after the Qt ones since these would append further flags. If that is the case, you maybe just want to append your flags to the Qt ones, so change to e.g.
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O0 -ggdb")
You can also use the "-u" option to specify the path. I find this helpful on machines where my .bashrc doesn't get sourced in non-interactive sessions. For example,
git clone -u /home/you/bin/git-upload-pack you@machine:code
import json
data = json.dumps(list)
print(data)
The above code snippet should work.
That's the easy answer:
$query="SELECT * FROM CountryInfo WHERE Name = '".$name."'";
and you define $name
whatever you want.
And another way, the complex way, is like that:
$query = " SELECT '" . $GLOBALS['Name'] . "' .* " .
" FROM CountryInfo " .
" INNER JOIN District " .
" ON District.CountryInfoId = CountryInfo.CountryInfoId " .
" INNER JOIN City " .
" ON City.DistrictId = District.DistrictId " .
" INNER JOIN '" . $GLOBALS['Name'] . "' " .
" ON '" . $GLOBALS['Name'] . "'.CityId = City.CityId " .
" WHERE CountryInfo.Name = '" . $GLOBALS['CountryName'] .
"'";
I was getting the same css file when I browse website(on hosting company server with real domain) and I was unable to get the updated version on chrome. I was able to get the updated version of the file when I browse it on Firefox. None of these answers worked for me. I also have the website files on my machine and browse the site with localhost using my local apache server. I shut down my apache server and I was able to get the updated file. Somehow my local apache server was messing with the chrome cache. Hope this helps someone as it was very hard for me to fix this.
For folks who are stumbling across Victor Stoddard's answer above in 2019, and become hopeful and doe eyed, note that:
a) Support for X-Content-Duration was removed in Firefox 41: https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Releases/41#HTTP
b) I think it was only supported in Firefox for .ogg audio and .ogv video, not for any other types.
c) I can't see that it was ever supported at all in Chrome, but that may just be a lack of research on my part. But its presence or absence seems to have no effect one way or another for webm or ogv videos as of today in Chrome 71.
d) I can't find anywhere where 'Content-Duration' replaced 'X-Content-Duration' for anything, I don't think 'X-Content-Duration' lived long enough for there to be a successor header name.
I think this means that, as of today if you want to serve webm or ogv containers that contain streams that don't know their duration (e.g. the output of an ffpeg pipe) to Chrome or FF, and you want them to be scrubbable in an HTML 5 video element, you are probably out of luck. Firefox 64.0 makes a half hearted attempt to make these scrubbable whether or not you serve via range requests, but it gets confused and throws up a spinning wheel until the stream is completely downloaded if you seek a few times more than it thinks is appropriate. Chrome doesn't even try, it just nopes out and won't let you scrub at all until the entire stream is finished playing.
you can use this as well
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var queryValue = getParameterByName('test_user_bLzgB');
It is not natively possible to run Android application under iOS (which powers iPhone, iPad, iPod, etc.)
This is because both runtime stacks use entirely different approaches. Android runs Dalvik (a "variant of Java") bytecode packaged in APK files while iOS runs Compiled (from Obj-C) code from IPA files. Excepting time/effort/money and litigations (!), there is nothing inherently preventing an Android implementation on Apple hardware, however.
It looks to package a small Dalvik VM with each application and targeted towards developers.
See iPhoDroid:
Looks to be a dual-boot solution for 2G/3G jailbroken devices. Very little information available, but there are some YouTube videos.
See iAndroid:
iAndroid is a new iOS application for jailbroken devices that simulates the Android operating system experience on the iPhone or iPod touch. While it’s still very far from completion, the project is taking shape.
I am not sure the approach(es) it uses to enable this: it could be emulation or just a simulation (e.g. "looks like"). The requirement of being jailbroken makes it sound like emulation might be used ..
See BlueStacks, per the Holo Dev's comment:
It looks to be an "Android App Player" for OS X (and Windows). However, afaik, it does not [currently] target iOS devices ..
YMMV
You can use browser default prompt window.
Instead of basic <input type="submit" (...) >
try:
<button onClick="if(confirm(\'are you sure ?\')){ this.form.submit() }">Save</button>
Just include following in your code
<body background="C:\Users\Desktop\images.jpg">
if you want to specify the size and opacity you can use following
<p><img style="opacity:0.9;" src="C:\Users\Desktop\images.jpg" width="300" height="231" alt="Image" /></p>
I had the same problem on windows 10. My eclipse version was installed from an exe, downloaded from eclipse site.
What solved for me was to use the zip version instead: http://www.eclipse.org/downloads/eclipse-packages/
These settings worked for me:
wv.setInitialScale(1);
wv.getSettings().setLoadWithOverviewMode(true);
wv.getSettings().setUseWideViewPort(true);
wv.getSettings().setJavaScriptEnabled(true);
setInitialScale(1) was missing in my attempts.
Although documentation says that 0 will zoom all the way out if setUseWideViewPort is set to true but 0 did not work for me and I had to set 1.
First, you need to call the owl.autoplay.js.
this code works for me : owl.trigger('play.owl.autoplay',[1000]);
I'm not a JavaScript expert, but it looks like you would have to loop through the elements and count them since Object doesn't have a length method:
var element_count = 0;
for (e in myArray) { if (myArray.hasOwnProperty(e)) element_count++; }
@palmsey: In fairness to the OP, the JavaScript documentation actually explicitly refer to using variables of type Object in this manner as "associative arrays".
Try this:
setlocal EnableDelayedExpansion
...
for /F "tokens=*" %%a in ('type %FileName%') do (
set z=%%a
echo !z!
echo %%a
)
In case you are looking for a cut and paste method that creates and writes to a file, here's one I wrote that just takes a String input. Remove 'true' from PrintWriter if you want to overwrite the file each time.
private static final String newLine = System.getProperty("line.separator");
private synchronized void writeToFile(String msg) {
String fileName = "c:\\TEMP\\runOutput.txt";
PrintWriter printWriter = null;
File file = new File(fileName);
try {
if (!file.exists()) file.createNewFile();
printWriter = new PrintWriter(new FileOutputStream(fileName, true));
printWriter.write(newLine + msg);
} catch (IOException ioex) {
ioex.printStackTrace();
} finally {
if (printWriter != null) {
printWriter.flush();
printWriter.close();
}
}
}
In case it helps anyone, in addition to deleting .settings
and .project
, I had to delete .classpath
and .factorypath
before being able to import the project successfully into Eclipse.
You can do it by making the background into a pattern:
<defs>
<pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
<image href="wall.jpg" x="0" y="0" width="100" height="100" />
</pattern>
</defs>
Adjust the width and height according to your image, then reference it from the path like this:
<path d="M5,50
l0,100 l100,0 l0,-100 l-100,0
M215,100
a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
M265,50
l50,100 l-100,0 l50,-100
z"
fill="url(#img1)" />
I see good answers have already been given, but I thought it might be nice to just give a way to perform mean filtering in MATLAB using no special functions or toolboxes. This is also very good for understanding exactly how the process works as you are required to explicitly set the convolution kernel. The mean filter kernel is fortunately very easy:
I = imread(...)
kernel = ones(3, 3) / 9; % 3x3 mean kernel
J = conv2(I, kernel, 'same'); % Convolve keeping size of I
Note that for colour images you would have to apply this to each of the channels in the image.
Note that reversing the whole string (either with the rbegin()
/rend()
range constructor or with std::reverse
) and comparing it with the input would perform unnecessary work.
It's sufficient to compare the first half of the string with the latter half, in reverse:
#include <string>
#include <algorithm>
#include <iostream>
int main()
{
std::string s;
std::cin >> s;
if( equal(s.begin(), s.begin() + s.size()/2, s.rbegin()) )
std::cout << "is a palindrome.\n";
else
std::cout << "is NOT a palindrome.\n";
}
demo: http://ideone.com/mq8qK
To add a stacktrace click on the Gradle on the right side of Android project screen;
Click on the settings icon; this will open the settings page,
Then click on compiler
Then add the command --stacktrace
or --debug
as shown;
Run the application again to get the gradle report.
Class names should be nouns in UpperCamelCase, with the first letter of every word capitalised. Use whole words — avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML). The naming conventions can be read over here:
http://www.oracle.com/technetwork/java/codeconventions-135099.html
I am not adding a new answer. I am just putting the best marked answer in a better format.
I can see that the best answer by rating is using sys.stdout.write(someString)
. You can try this out:
import sys
Print = sys.stdout.write
Print("Hello")
Print("World")
will yield:
HelloWorld
That is all.
var my_arr = new Array(listingID, site_click, browser, dimension);
var AjaxURL = 'http://example.com';
var jsonString = JSON.stringify(my_arr);
$.ajax({
type: "POST",
url: AjaxURL,
data: {data: jsonString},
success: function(result) {
window.console.log('Successful');
}
});
This has been working for me for quite some time.
In case someone else finds this topic while using localhost
in the file URIs - Internet Explorer acts completely different if the host name is localhost
or 127.0.0.1
- if you use the actual hostname, it works fine (from trusted sites/intranet zone).
Another big difference between IE and FF - IE is fine with uris like file://server/share/file.txt
but FF requires additional slashes file:////server/share/file.txt
.
I had a similar problem.
As it turned out, I ran mvn clean package install.
Correct way is mvn clean install
The set of paths where the compiler looks for the header files can be checked by the command:-
cpp -v
If you declare #include "" , the compiler first searches in current directory of source file and if not found, continues to search in the above retrieved directories.
If you declare #include <> , the compiler searches directly in those directories obtained from the above command.
Source:- http://commandlinefanatic.com/cgi-bin/showarticle.cgi?article=art026
Are you attempting to do this inside of an XCTest and on the verge of smashing your laptop? This is the thread for you: Why can't code inside unit tests find bundle resources?
I had the same problem in java and I solved it with a bit of logic and regex. I believe the same logic can be applied.First I read from the slq file into memory. Then I apply the following logic. It's pretty much what has been said before however I believe that using regex word bound is safer than expecting a new line char.
String pattern = "\\bGO\\b|\\bgo\\b";
String[] splitedSql = sql.split(pattern);
for (String chunk : splitedSql) {
getJdbcTemplate().update(chunk);
}
This basically splits the sql string into an array of sql strings. The regex is basically to detect full 'go' words either lower case or upper case. Then you execute the different querys sequentially.
For me it was Auto Tab Discard
, which throws that error on pinned tabs. I created a bug report, https://github.com/rNeomy/auto-tab-discard/issues/101.
First you need to set a reference (Menu: Tools->References) to the Microsoft Excel Object Library then you can access all Excel Objects.
After you added the Reference you have full access to all Excel Objects. You need to add Excel in front of everything for example:
Dim xlApp as Excel.Application
Let's say you added an Excel Workbook Object in your Form and named it xLObject.
Here is how you Access a Sheet of this Object and change a Range
Dim sheet As Excel.Worksheet
Set sheet = xlObject.Object.Sheets(1)
sheet.Range("A1") = "Hello World"
(I copied the above from my answer to this question)
Another way to use Excel in Access is to start Excel through a Access Module (the way shahkalpesh described it in his answer)
The method getDeviceId()
is deprecated.
There a new method for this getImei(int)
from s in context.shift
where !context.employeeshift.Any(es=>(es.shiftid==s.shiftid)&&(es.empid==57))
select s;
Hope this helps
After placing the jar file in desired location, you need to add the jar file by right click on
Project --> properties --> Java Build Path --> Libraries --> Add Jar.
This is not the real problem, if you want to see why this is happening then please go to error log file of IIS.
in case of visual studio kindly navigate to:
C:\Users\User\Documents\IISExpress\TraceLogFiles\[your project name]\.
arrange file here in datewise descending and then open very first file.
it will look like:
now scroll down to bottom to see the GENERAL_RESPONSE_ENTITY_BUFFER
it is the actual problem. now solve it the above problem will solve automatically.
For Bootstrap 4, there are now spacing utilities so it's easier to change the height via padding on the nav links. This can be responsively applied only at specific breakpoints (ie: py-md-3
). For example, on larger (md) screens, this nav is 120px high, then shrinks to normal height for the mobile menu. No extra CSS is needed..
<nav class="navbar navbar-fixed-top navbar-inverse bg-primary navbar-toggleable-md py-md-3">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
<div class="navbar-collapse collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item py-md-3"><a href="#" class="nav-link">Home</a></li>
<li class="nav-item py-md-3"><a href="#" class="nav-link">Link</a></li>
<li class="nav-item py-md-3"><a href="#" class="nav-link">Link</a></li>
<li class="nav-item py-md-3"><a href="#" class="nav-link">More</a></li>
<li class="nav-item py-md-3"><a href="#" class="nav-link">Options</a></li>
</ul>
</div>
</nav>
I've searched a lot and the best way I've found so far is on this article:
Class to serialize
package net.sghill.example;
import net.sghill.example.UserDeserializer
import net.sghill.example.UserSerializer
import org.codehaus.jackson.map.annotate.JsonDeserialize;
import org.codehaus.jackson.map.annotate.JsonSerialize;
@JsonDeserialize(using = UserDeserializer.class)
public class User {
private ObjectId id;
private String username;
private String password;
public User(ObjectId id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public ObjectId getId() { return id; }
public String getUsername() { return username; }
public String getPassword() { return password; }
}
Deserializer class
package net.sghill.example;
import net.sghill.example.User;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.ObjectCodec;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;
import java.io.IOException;
public class UserDeserializer extends JsonDeserializer<User> {
@Override
public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
return new User(null, node.get("username").getTextValue(), node.get("password").getTextValue());
}
}
Edit: Alternatively you can look at this article which uses new versions of com.fasterxml.jackson.databind.JsonDeserializer.
PHP_EOL returns a string corresponding to the line break on the platform(LF, \n ou #10 sur Unix, CRLF, \n\r ou #13#10 sur Windows).
echo "Hello World".PHP_EOL;
and this is Joomla 3.3.2 version from JFile::makeSafe($file)
public static function makeSafe($file)
{
// Remove any trailing dots, as those aren't ever valid file names.
$file = rtrim($file, '.');
$regex = array('#(\.){2,}#', '#[^A-Za-z0-9\.\_\- ]#', '#^\.#');
return trim(preg_replace($regex, '', $file));
}
You could explicitly set the display property to "block" so it behaves like a block level element, but in that case you should probably just use a div instead.
<span style="display:block; background-color:red; width:100px;"></span>
From @Jon Skeet comment, really the String
value is "null"
. Following code solved it
if (userEmail != null && !userEmail.isEmpty() && !userEmail.equals("null"))
In the above given code
assign the php value to javascript variable.
<html>
<?php
$num = 1;
echo $num;
?>
<input type = "button" name = "lol" value = "Click to increment" onclick = "Inc()">
<br>
<script>
var numeric = <?php echo $num; ?>"; //assigns value of the $num to javascript var numeric
function Inc()
{
numeric = eVal(numeric) + 1;
alert("Increamented value: "+numeric);
}
</script>
</html>
One thing in combination of PHP and Javsacript is you can not assign javascript value to PHP value. You can assign PHP value to javascript variable.
Have a look at the advanced wheres documentation for Fluent: http://laravel.com/docs/queries#advanced-wheres
Here's an example of what you're trying to achieve:
DB::table('users')
->whereIn('id', function($query)
{
$query->select(DB::raw(1))
->from('orders')
->whereRaw('orders.user_id = users.id');
})
->get();
This will produce:
select * from users where id in (
select 1 from orders where orders.user_id = users.id
)
You can try with this
nFilter.style.cssText = 'width:330px;float:left;';
That should do it for you.
Came here to see how to append an item to a 2D array, but the title of the thread is a bit misleading because it is exploring an issue with the appending.
The easiest way I found to append to a 2D list is like this:
list=[[]]
list.append((var_1,var_2))
This will result in an entry with the 2 variables var_1, var_2. Hope this helps!
You don't actually declare things, but this is how you create an array in Python:
from array import array
intarray = array('i')
For more info see the array module: http://docs.python.org/library/array.html
Now possible you don't want an array, but a list, but others have answered that already. :)
width="50%" and height="50%" sets the width and height attributes to half of the parent element's width and height if I'm not mistaken. Also setting just width or height should set the width or height to the percentage of the parent element, if you're using percents.
Just worth mentioning that while others suggest tempering with files, I was able to resolve this issue by installing a missing plugin (ionic framework)
Hopefully it helps someone.
cordova plugin add cordova-support-google-services --save
You can also get this error with any version of git if the remote branch was created after your last clone/fetch and your local repo doesn't know about it yet. I solved it by doing a git fetch
first which "tells" your local repo about all the remote branches.
git fetch
git checkout test-branch
Just becuase your class object has no variables does not mean that it is nothing. Declaring and object and creating an object are two different things. Look and see if you are setting/creating the object.
Take for instance the dictionary object - just because it contains no variables does not mean it has not been created.
Sub test()
Dim dict As Object
Set dict = CreateObject("scripting.dictionary")
If Not dict Is Nothing Then
MsgBox "Dict is something!" '<--- This shows
Else
MsgBox "Dict is nothing!"
End If
End Sub
However if you declare an object but never create it, it's nothing.
Sub test()
Dim temp As Object
If Not temp Is Nothing Then
MsgBox "Temp is something!"
Else
MsgBox "Temp is nothing!" '<---- This shows
End If
End Sub
public string ToString(this string value)
{
if (value == null)
{
value = string.Empty;
}
else
{
return value.Trim();
}
}
Following commands worked for me :
> npm config set strict-ssl false
> npm cache clean --force
The problem is that you are attempting to install a module from a repository with a bad or untrusted SSL[Secure Sockets Layer] certificate. Once you clean the cache, this problem will be resolved.You might need to turn it to true later on.
Use the id instead:
This is the easiest method that can handle even if the list is long:
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.list_item, null);
//Handle your items.
//StringHolder.mSelectedItem is a public static variable.
if(getItemId(position)==StringHolder.mSelectedItem){
rowView.setBackgroundColor(Color.LTGRAY);
}else{
rowView.setBackgroundColor(Color.TRANSPARENT);
}
return rowView;
}
And then in your onclicklistener:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
StringHolder.mSelectedItem = catagoryAdapter.getItemId(i-1);
catagoryAdapter.notifyDataSetChanged();
.....
This is a Pythonic way to do it:
import httplib
import yaml
c = httplib.HTTPConnection(address)
c.request('GET', url_path)
r = c.getresponse()
# get the date into a datetime object
lmd = r.getheader('last-modified')
if lmd != None:
cur_data = { url: datetime.strptime(lmd, '%a, %d %b %Y %H:%M:%S %Z') }
else:
print "Hmmm, no last-modified data was returned from the URL."
print "Returned header:"
print yaml.dump(dict(r.getheaders()), default_flow_style=False)
The rest of the script includes an example of archiving a page and checking for changes against the new version, and alerting someone by email.
No need for the option, just make the preferred width of the last column the maximum and it will take all the extra space.
table.getColumnModel().getColumn(0).setPreferredWidth(27);
table.getColumnModel().getColumn(1).setPreferredWidth(120);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setPreferredWidth(90);
table.getColumnModel().getColumn(4).setPreferredWidth(90);
table.getColumnModel().getColumn(6).setPreferredWidth(120);
table.getColumnModel().getColumn(7).setPreferredWidth(100);
table.getColumnModel().getColumn(8).setPreferredWidth(95);
table.getColumnModel().getColumn(9).setPreferredWidth(40);
table.getColumnModel().getColumn(10).setPreferredWidth(Integer.MAX_INT);
In my case the issue was that Virtual directory was not created.
Just copy the part you want from the webpage and paste it in the wysiwyg editor. Check the html source by clicking on the "source" button on the editor toolbar.
I've found this most easiest way when I was working on a Drupal site. I use wysiwyg CKeditor.
with ng CLI
> npm install moment --save
in app.module
import * as moment from 'moment';
providers: [{ provide: 'moment', useValue: moment }]
in component
constructor(@Inject('moment') private moment)
this way you import moment once
UPDATE Angular => 5
{
provide: 'moment', useFactory: (): any => moment
}
For me works in prod with aot and also with universal
I dont like using any but using moment.Moment I got
Error Typescript Type 'typeof moment' is not assignable to type 'Moment'. Property 'format' is missing in type 'typeof moment'.
Similar to the accepted question but it allows you to scale without the need of adding a new module to the index file each time you create one:
./modules/moduleA.js
export const example = 'example';
export const anotherExample = 'anotherExample';
./modules/index.js
// require all modules on the path and with the pattern defined
const req = require.context('./', true, /.js$/);
const modules = req.keys().map(req);
// export all modules
module.exports = modules;
./example.js
import { example, anotherExample } from './modules'
There are several reasons to want to know what the device is.
You can check the device height (and width). This is useful for layout, but you usually don't want to do that if you want to know the exact device.
For layout purposes, you can also use UIView.safeAreaInsets
.
If you want to display the device name, for example, to be included in a email for diagnostic purposes, after retrieving the device model using sysctl ()
, you can use the equivalent of this to figure the name:
$ curl http://appledevicenames.com/devices/iPhone10,6
iPhone X
The documentation says
The output format of the date/time types can be set to one of the four styles ISO 8601, SQL (Ingres), traditional POSTGRES (Unix date format), or German. The default is the ISO format.
So this particular format can be controlled with postgres
date time output, eg:
t=# select now();
now
-------------------------------
2017-11-29 09:15:25.348342+00
(1 row)
t=# set datestyle to DMY, SQL;
SET
t=# select now();
now
-------------------------------
29/11/2017 09:15:31.28477 UTC
(1 row)
t=# select now()::date;
now
------------
29/11/2017
(1 row)
Mind that as @Craig mentioned in his answer, changing datestyle
will also (and in first turn) change the way postgres parses date.
See the following methods:
~ : Changes the case of current character
guu : Change current line from upper to lower.
gUU : Change current LINE from lower to upper.
guw : Change to end of current WORD from upper to lower.
guaw : Change all of current WORD to lower.
gUw : Change to end of current WORD from lower to upper.
gUaw : Change all of current WORD to upper.
g~~ : Invert case to entire line
g~w : Invert case to current WORD
guG : Change to lowercase until the end of document.
here's how we have been dealing with the UK postcode issue:
^([A-Za-z]{1,2}[0-9]{1,2}[A-Za-z]?[ ]?)([0-9]{1}[A-Za-z]{2})$
Explanation:
This gets most formats, we then use the db to validate whether the postcode is actually real, this data is driven by openpoint https://www.ordnancesurvey.co.uk/opendatadownload/products.html
hope this helps
For an unknow reason, the accepted answer partially works when I send email to my gmail address. I have the attachement but not the text of the email.
If you want both attachment and text try this based on the accepted answer :
Properties props = new java.util.Properties();
props.put("mail.smtp.host", "yourHost");
props.put("mail.smtp.port", "yourHostPort");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
// Session session = Session.getDefaultInstance(props, null);
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user", "password");
}
});
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(mailFrom));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
msg.setSubject("your subject");
Multipart multipart = new MimeMultipart();
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setText("your text");
MimeBodyPart attachmentBodyPart= new MimeBodyPart();
DataSource source = new FileDataSource(attachementPath); // ex : "C:\\test.pdf"
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(fileName); // ex : "test.pdf"
multipart.addBodyPart(textBodyPart); // add the text part
multipart.addBodyPart(attachmentBodyPart); // add the attachement part
msg.setContent(multipart);
Transport.send(msg);
} catch (MessagingException e) {
LOGGER.log(Level.SEVERE,"Error while sending email",e);
}
Update :
If you want to send a mail as an html content formated you have to do
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setContent(content, "text/html");
So basically setText
is for raw text and will be well display on every server email including gmail, setContent
is more for an html template and if you content is formatted as html it will maybe also works in gmail
If you mean that you want to enable the submit after the user has typed at least one character, then you need to attach a key event that will check it for you.
Something like:
$("#fbss").keypress(function() {
if($(this).val().length > 1) {
// Enable submit button
} else {
// Disable submit button
}
});
As others already said, there seems to be no good solution to do that easily.
But to keep your code clean I suggest creating a seperate class that hides the ugly XAML.
How to use after we created the ButtonEx-class:
<Window x:Class="MyApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:wpfEx="clr-namespace:WpfExtensions"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<wpfEx:ButtonEx HoverBackground="Red"></wpfEx:ButtonEx>
</Grid>
</Window>
ButtonEx.xaml.cs
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace WpfExtensions
{
/// <summary>
/// Standard button with extensions
/// </summary>
public partial class ButtonEx : Button
{
readonly static Brush DefaultHoverBackgroundValue = new BrushConverter().ConvertFromString("#FFBEE6FD") as Brush;
public ButtonEx()
{
InitializeComponent();
}
public Brush HoverBackground
{
get { return (Brush)GetValue(HoverBackgroundProperty); }
set { SetValue(HoverBackgroundProperty, value); }
}
public static readonly DependencyProperty HoverBackgroundProperty = DependencyProperty.Register(
"HoverBackground", typeof(Brush), typeof(ButtonEx), new PropertyMetadata(DefaultHoverBackgroundValue));
}
}
ButtonEx.xaml
Note: This contains all the original XAML from System.Windows.Controls.Button
<Button x:Class="WpfExtensions.ButtonEx"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
x:Name="buttonExtension">
<Button.Resources>
<Style x:Key="FocusVisual">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<Rectangle Margin="2" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="10" StrokeDashArray="1 2"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<SolidColorBrush x:Key="Button.Static.Background" Color="#FFDDDDDD"/>
<SolidColorBrush x:Key="Button.Static.Border" Color="#FF707070"/>
<SolidColorBrush x:Key="Button.MouseOver.Background" Color="#FFBEE6FD"/>
<SolidColorBrush x:Key="Button.MouseOver.Border" Color="#FF3C7FB1"/>
<SolidColorBrush x:Key="Button.Pressed.Background" Color="#FFC4E5F6"/>
<SolidColorBrush x:Key="Button.Pressed.Border" Color="#FF2C628B"/>
<SolidColorBrush x:Key="Button.Disabled.Background" Color="#FFF4F4F4"/>
<SolidColorBrush x:Key="Button.Disabled.Border" Color="#FFADB2B5"/>
<SolidColorBrush x:Key="Button.Disabled.Foreground" Color="#FF838383"/>
</Button.Resources>
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/>
<Setter Property="Background" Value="{StaticResource Button.Static.Background}"/>
<Setter Property="BorderBrush" Value="{StaticResource Button.Static.Border}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Padding" Value="1"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
<ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsDefaulted" Value="true">
<Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Background" TargetName="border" Value="{Binding Path=HoverBackground, ElementName=buttonExtension}"/>
<Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
</Trigger>
<Trigger Property="IsPressed" Value="true">
<Setter Property="Background" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/>
<Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Background" TargetName="border" Value="{StaticResource Button.Disabled.Background}"/>
<Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Disabled.Border}"/>
<Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="{StaticResource Button.Disabled.Foreground}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Button.Style>
</Button>
Tip: You can add an UserControl with name "ButtonEx" to your project in VS Studio and then copy paste the stuff above in.
FailedDev's answer is good, but can be improved. If you want to preserve the ascii equivalents, you need to normalize first:
String subjectString = "öäü";
subjectString = Normalizer.normalize(subjectString, Normalizer.Form.NFD);
String resultString = subjectString.replaceAll("[^\\x00-\\x7F]", "");
=> will produce "oau"
That way, characters like "öäü" will be mapped to "oau", which at least preserves some information. Without normalization, the resulting String will be blank.
alternatively include event.preventDefault(); in your handleSubmit(event) {
Some color-syntaxing enrichment can be applied with the following blockcode syntax
```json
Here goes your json object definition
```
Note: This won't prettify the json representation. To do so, one can previously rely on an external service such as jsbeautifier.org and paste the prettified result in the wiki.
Other solutions for Git Bash provided by others didn't work for me. Apparently there is currently a bug/limitation in Git for Windows. See this and this.
I finally managed to get it working after finding this GitHub thread (which provides some additional solutions if you're interested, which might work for you, but didn't for me).
I ended up using the following syntax:
MSYS_NO_PATHCONV=1 docker run --rm -it -v $(pwd):/usr/src/project gcc:4.9
Note the MSYS_NO_PATHCONV=1
in front of the docker
command and $(pwd)
- round brackets, lower-case pwd, no quotes, no backslashes.
Also, I'm using Linux containers on Windows if that matters..
I tested this in the new Windows Terminal, ConEmu and GitBash, and all of them worked for me.
I think you can do something like this, the syntax might be wrong, havent used C# in a while To get the last item
Dictionary<string, int>.KeyCollection keys = mydict.keys;
string lastKey = keys.Last();
or use Max instead of Last to get the max value, I dont know which one fits your code better.
The default web folder for nginx depends on how you installed it, but normally it's in these locations:
/usr/local/nginx/html
/usr/nginx/html
The word "read" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it.
from PIL import Image
jpgfile = Image.open("picture.jpg")
print(jpgfile.bits, jpgfile.size, jpgfile.format)
Also note that setting a header to "text/plain"
will result in all html and php (in part) printing the characters on the screen as TEXT, not as HTML. So be aware of possible HTML not parsing when using text type plain
.
Using:
header('Content-type: text/html; charset=utf-8');
Can return HTML and PHP as well. Not just text.
Try SQLDeveloper - there is a migration workbench there
http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index.html
Create user dependency upon the database connect tools
sql plus
SQL> connect as sysdba;
Enter user-name: sysdba
Enter password:
Connected.
SQL> ALTER USER hr account unlock identified by hr;
User altered
then create user on sql plus and sql developer
For MVC here was an even easier approach. You need to use the Ajax form and set the AjaxOptions
@using (Ajax.BeginForm("UploadTrainingMedia", "CreateTest", new AjaxOptions() { HttpMethod = "POST", OnComplete = "displayUploadMediaMsg" }, new { enctype = "multipart/form-data", id = "frmUploadTrainingMedia" }))
{
... html for form
}
here is the submission code, this is in the document ready section and ties the onclick event of the button to to submit the form
$("#btnSubmitFileUpload").click(function(e){
e.preventDefault();
$("#frmUploadTrainingMedia").submit();
});
here is the callback referenced in the AjaxOptions
function displayUploadMediaMsg(d){
var rslt = $.parseJSON(d.responseText);
if (rslt.statusCode == 200){
$().toastmessage("showSuccessToast", rslt.status);
}
else{
$().toastmessage("showErrorToast", rslt.status);
}
}
in the controller method for MVC it looks like this
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult UploadTrainingMedia(IEnumerable<HttpPostedFileBase> files)
{
if (files != null)
{
foreach (var file in files)
{
// there is only one file ... do something with it
}
return Json(new
{
statusCode = 200,
status = "File uploaded",
file = "",
}, "text/html");
}
else
{
return Json(new
{
statusCode = 400,
status = "Unable to upload file",
file = "",
}, "text/html");
}
}
Many thanks to @Ciro Santilli answer! I found that his choice for boundary is quite "unhappy" because all of thoose hyphens: in fact, as @Fake Name commented, when you are using your boundary inside request it comes with two more hyphens on front:
Example:
POST / HTTP/1.1
HOST: host.example.com
Cookie: some_cookies...
Connection: Keep-Alive
Content-Type: multipart/form-data; boundary=12345
--12345
Content-Disposition: form-data; name="sometext"
some text that you wrote in your html form ...
--12345
Content-Disposition: form-data; name="name_of_post_request" filename="filename.xyz"
content of filename.xyz that you upload in your form with input[type=file]
--12345
Content-Disposition: form-data; name="image" filename="picture_of_sunset.jpg"
content of picture_of_sunset.jpg ...
--12345--
I found on this w3.org page that is possible to incapsulate multipart/mixed header in a multipart/form-data, simply choosing another boundary string inside multipart/mixed and using that one to incapsulate data. At the end, you must "close" all boundary used in FILO order to close the POST request (like:
POST / HTTP/1.1
...
Content-Type: multipart/form-data; boundary=12345
--12345
Content-Disposition: form-data; name="sometext"
some text sent via post...
--12345
Content-Disposition: form-data; name="files"
Content-Type: multipart/mixed; boundary=abcde
--abcde
Content-Disposition: file; file="picture.jpg"
content of jpg...
--abcde
Content-Disposition: file; file="test.py"
content of test.py file ....
--abcde--
--12345--
Take a look at the link above.
For me, this error was caused by running the minified version of my angular app. Angular docs suggest a way to work around this. Here is the relevant quote describing the issue, and you can find the suggested solution in the docs themselves here:
A Note on Minification Since Angular infers the controller's dependencies from the names of arguments to the controller's constructor function, if you were to minify the JavaScript code for PhoneListCtrl controller, all of its function arguments would be minified as well, and the dependency injector would not be able to identify services correctly.
UPDATE 9 July 2012 - Looks like this is fixed in RTM.
^
and $
so you don't need to add them. (It doesn't appear to be a problem to include them, but you don't need them)View source shows the following:
data-val-regex-pattern="([a-zA-Z0-9 .&'-]+)" <-- MVC 3
data-val-regex-pattern="([a-zA-Z0-9 .&amp;&#39;-]+)" <-- MVC 4/Beta
It looks like we're double encoding.
I'm using the following to execute commands on the remote from my local computer:
ssh -i ~/.ssh/$GIT_PRIVKEY user@$IP "bash -s" < localpath/script.sh $arg1 $arg2
Here's another method that's unorthodox, but works*.
I recently found myself in a situation where I'd checked in breaking code, knowing that I couldn't update our production code to it until all the integration work had taken place (in retrospect this was a bad decision, but we didn't expect to get stalled out, but other projects took precedence). That was several months ago, and the integration has been stalled for that entire time. Along comes a requirement to change the base code and get it into production last week without the breaking change.
Here's what we did:
After verifying that the new requirement doesn't break anything when using the revision before my check in, I made a copy of the working directory containing the new code. Then I deleted everything in the working directory and checked out the revision I wanted to it. Then I deleted all the files I'd just checked out, and copied in the files from the working copy. Then I committed that change, effectively wiping out the breaking change from the repository and getting the production code in place as the head revision. We still have the breaking change available, but it's no longer in the head revision so we can move forward to production.
*I don't recommend this method, but if you find yourself in a similar situation, it's a way out that's not too painful.
Note that the beauty of std::reverse is that it works with char *
strings and std::wstring
s just as well as std::string
s
void strrev(char *str)
{
if (str == NULL)
return;
std::reverse(str, str + strlen(str));
}
Using the YUI library (I love it):
YAHOO.util.Event.onDOMReady(function(){
//your code
});
Portable and beautiful! However, if you don't use YUI for other stuff (see its doc) I would say that it's not worth to use it.
N.B. : to use this code you need to import 2 scripts
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/yahoo/yahoo-min.js" ></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/event/event-min.js" ></script>
Here is how to do it using TCP IP protocol :
// Printer IP Address and communication port
string ipAddress = "10.3.14.42";
int port = 9100;
// ZPL Command(s)
string ZPLString =
"^XA" +
"^FO50,50" +
"^A0N50,50" +
"^FDHello, World!^FS" +
"^XZ";
try
{
// Open connection
System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
client.Connect(ipAddress, port);
// Write ZPL String to connection
System.IO.StreamWriter writer =
new System.IO.StreamWriter(client.GetStream());
writer.Write(ZPLString);
writer.Flush();
// Close Connection
writer.Close();
client.Close();
}
catch (Exception ex)
{
// Catch Exception
}
Source : ZEBRA WEBSITE
Both these will give you the first child node:
console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);
If you need the first child that is an element node then use:
console.log(parentElement.children[0]);
Edit
Ah, I see your problem now; parentElement
is an array.
If you know that getElementsByClassName will only return one result, which it seems you do, you should use [0]
to dearray (yes, I made that word up) the element:
var parentElement = document.getElementsByClassName("uniqueClassName")[0];
I had the same problem i solved it in that way: My ajax:
event.preventDefault();
$.ajax('file.php', {
method: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({tab}),
success: function(php_response){
if (php_response == 'item')
{
console.log('it works');
}
}
})
Ok. The problem is not with json but only php response. Before: my php response was:
echo 'item';
Now:
$variable = 'item';
echo json.encode($variable);
Now my success working. PS. Sorry if something is wrong but it is my first comment on this forum :)
One can use margin in order to change the width of a line and place it center.
import { StyleSheet } from 'react-native;
<View style = {styles.lineStyle} />
const styles = StyleSheet.create({
lineStyle:{
borderWidth: 0.5,
borderColor:'black',
margin:10,
}
});
if you want to give margin dynamically then you can use Dimension width.
Epsilon is a difference between expected
and actual
values which you can accept thinking they are equal. You can set .1
for example.
Currently the best documentation is the source. You can take a look at it here (attrs.xml).
You can define attributes in the top <resources>
element or inside of a <declare-styleable>
element. If I'm going to use an attr in more than one place I put it in the root element. Note, all attributes share the same global namespace. That means that even if you create a new attribute inside of a <declare-styleable>
element it can be used outside of it and you cannot create another attribute with the same name of a different type.
An <attr>
element has two xml attributes name
and format
. name
lets you call it something and this is how you end up referring to it in code, e.g., R.attr.my_attribute
. The format
attribute can have different values depending on the 'type' of attribute you want.
You can set the format to multiple types by using |
, e.g., format="reference|color"
.
enum
attributes can be defined as follows:
<attr name="my_enum_attr">
<enum name="value1" value="1" />
<enum name="value2" value="2" />
</attr>
flag
attributes are similar except the values need to be defined so they can be bit ored together:
<attr name="my_flag_attr">
<flag name="fuzzy" value="0x01" />
<flag name="cold" value="0x02" />
</attr>
In addition to attributes there is the <declare-styleable>
element. This allows you to define attributes a custom view can use. You do this by specifying an <attr>
element, if it was previously defined you do not specify the format
. If you wish to reuse an android attr, for example, android:gravity, then you can do that in the name
, as follows.
An example of a custom view <declare-styleable>
:
<declare-styleable name="MyCustomView">
<attr name="my_custom_attribute" />
<attr name="android:gravity" />
</declare-styleable>
When defining your custom attributes in XML on your custom view you need to do a few things. First you must declare a namespace to find your attributes. You do this on the root layout element. Normally there is only xmlns:android="http://schemas.android.com/apk/res/android"
. You must now also add xmlns:whatever="http://schemas.android.com/apk/res-auto"
.
Example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:whatever="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<org.example.mypackage.MyCustomView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
whatever:my_custom_attribute="Hello, world!" />
</LinearLayout>
Finally, to access that custom attribute you normally do so in the constructor of your custom view as follows.
public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView, defStyle, 0);
String str = a.getString(R.styleable.MyCustomView_my_custom_attribute);
//do something with str
a.recycle();
}
The end. :)
It is BAD habit and terribly ANNOYING practice to quote Joshua Bloch without understanding the basic ground-zero fundamentalism.
I have not read anything Joshua Bloch, so either
As in Bible fundamentalism all the biblical laws can be summed up by
and so similarly software engineering fundamentalism can be summed up by
Also, among biblical fundamentalist circles a strong and reasonable corollary is drawn
Similarly, if you do not respect yourself as a programmer and just accept the pronouncements and prophecies of some programming guru-nath WITHOUT questioning the fundamentals, your quotations and reliance on Joshua Bloch (and the like) is meaningless. And therefore, you would actually have no respect for your fellow-programmers.
The fundamental laws of software programming
Under what laws of fundamentally effective and responsible programming does this religious edict fall into ?
Just read the wikipedia article on interface-pattern constants (https://en.wikipedia.org/wiki/Constant_interface), and the silly excuses it states against interface-pattern constants.
Whatif-No IDE? Who on earth as a software programmer would not use an IDE? Most of us are programmers who prefer not to have to prove having macho aescetic survivalisticism thro avoiding the use of an IDE.
Pollutes the namespace with variables not used within the current scope? It could be proponents of this opinion
Using interfaces for enforcing constants is an abuse of interfaces. Proponents of such have a bad habit of
It is difficult if not impossible to convert interfaces into implemented classes in the future. Hah .... hmmm ... ???
Whatever the excuses, there is NO VALID EXCUSE when it comes to FUNDAMENTALLY EFFECTIVE software engineering to delegitimize or generally discourage the use of interface constants.
It doesn't matter what the original intents and mental states of the founding fathers who crafted the United States Constitution were. We could debate the original intents of the founding fathers but all I care is the written statements of the US Constitution. And it is the responsibility of every US citizen to exploit the written literary-fundamentalism, not the unwritten founding-intents, of the US Constitution.
Similarly, I do not care what the "original" intents of the founders of the Java platform and programming language had for the interface. What I care are the effective features the Java specification provides, and I intend to exploit those features to the fullest to help me fulfill the fundamental laws of responsible software programming. I don't care if I am perceived to "violate the intention for interfaces". I don't care what Gosling or someone Bloch says about the "proper way to use Java", unless what they say does not violate my need to EFFECTIVE fulfilling fundamentals.
It doesn't matter how your data-model is hosted or transmitted. Whether you use interfaces or enums or whatevernots, relational or no-SQL, if you don't understand the need and process of data-model normalization.
We must first define and normalize the data-model of a set of processes. And when we have a coherent data-model, ONLY then can we use the process flow of its components to define the functional behaviour and process blocks a field or realm of applications. And only then can we define the API of each functional process.
Even the facets of data normalization as proposed by EF Codd is now severely challenged and severely-challenged. e.g. his statement on 1NF has been criticized as ambiguous, misaligned and over-simplified, as is the rest of his statements especially in the advent of modern data services, repo-technology and transmission. IMO, the EF Codd statements should be completely ditched and new set of more mathematically plausible statements be designed.
A glaring flaw of EF Codd's and the cause of its misalignment to effective human comprehension is his belief that humanly perceivable multi-dimensional, mutable-dimension data can be efficiently perceived thro a set of piecemeal 2-dimensional mappings.
What EF Codd failed to express.
Within each coherent data-model, these are the sequential graduated order of data-model coherence to achieve.
In a field or grid of inter-servicing component-applications, there must be one and only one coherent data-model or exists a means for a data-model/version to identify itself.
There are data-normalization issues at stake more consequential than this mundane question. IF you don't solve those issues, the confusion that you think interface constants cause is comparatively nothing. Zilch.
From the data-model normalization then you determine the components as variables, as properties, as contract interface constants.
Then you determine which goes into value injection, property configuration placeholding, interfaces, final strings, etc.
If you have to use the excuse of needing to locate a component easier to dictate against interface constants, it means you are in the bad habit of not practicing data-model normalization.
Perhaps you wish to compile the data-model into a vcs release. That you can pull out a distinctly identifiable version of a data-model.
Values defined in interfaces are completely assured to be non-mutable. And shareable. Why load a set of final strings into your class from another class when all you need is that set of constants ??
So why not this to publish a data-model contract? I mean if you can manage and normalize it coherently, why not? ...
public interface CustomerService {
public interface Label{
char AssignmentCharacter = ':';
public interface Address{
String Street = "Street";
String Unit= "Unit/Suite";
String Municipal = "City";
String County = "County";
String Provincial = "State";
String PostalCode = "Zip"
}
public interface Person {
public interface NameParts{
String Given = "First/Given name"
String Auxiliary = "Middle initial"
String Family = "Last name"
}
}
}
}
Now I can reference my apps' contracted labels in a way such as
CustomerService.Label.Address.Street
CustomerService.Label.Person.NameParts.Family
This confuses the contents of the jar file? As a Java programmer I don't care about the structure of the jar.
This presents complexity to osgi-motivated runtime swapping ? Osgi is an extremely efficient means to allow programmers to continue in their bad habits. There are better alternatives than osgi.
Or why not this? There is no leakage of of the private Constants into published contract. All private constants should be grouped into a private interface named "Constants", because I don't want to have to search for constants and I am too lazy to repeatedly type "private final String".
public class PurchaseRequest {
private interface Constants{
String INTERESTINGName = "Interesting Name";
String OFFICIALLanguage = "Official Language"
int MAXNames = 9;
}
}
Perhaps even this:
public interface PurchaseOrderConstants {
public interface Properties{
default String InterestingName(){
return something();
}
String OFFICIALLanguage = "Official Language"
int MAXNames = 9;
}
}
The only issue with interface constants worth considering is when the interface is implemented.
This is not the "original intention" of interfaces? Like I would care about the "original intention" of the founding fathers in crafting the US Constitution, rather than how the Supreme Court would interpret the written letters of the US Constitution ???
After all, I live in the land of the free, the wild and home of the brave. Be brave, be free, be wild - use the interface. If my fellow-programmers refuse to use efficient and lazy means of programming, am I obliged by the golden rule to lessen my programming efficiency to align with theirs? Perhaps I should, but that is not an ideal situation.
Having the same issue here. As pointed out by @Izabela Orlowska, this problem is most likely caused by special characters in path (android grandle files, resources etc..).
For me: having rí
in folder name caused all the problems. Make sure you do not have any special characters in paths. Disabling AAPT2 is only a temporary "solution". Your project path contains non-ASCII characters android studio
You can try this also
SELECT id , IF(type='p', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount FROM table
The problem you are describing sounds like your version of PHP might be missing the readline PHP module, causing the interactive shell to not work. I base this on this PHP bug submission.
Try running
php -m
And see if "readline" appears in the output.
There might be good reasons for omitting readline from the distribution. PHP is typically executed by a web server; so it is not really need for most use cases. I am sure you can execute PHP code in a file from the command prompt, using:
php file.php
There is also the phpsh project which provides a (better) interactive shell for PHP. However, some people have had trouble running it under Windows (I did not try this myself).
Edit:
According to the documentation here, readline
is not supported under Windows:
Note: This extension is not available on Windows platforms.
So, if that is correct, your options are:
int
is a primitive, null is not a value that it can take on. You could change the method return type to return java.lang.Integer
and then you can return null, and existing code that returns int will get autoboxed.
Nulls are assigned only to reference types, it means the reference doesn't point to anything. Primitives are not reference types, they are values, so they are never set to null.
Using the object wrapper java.lang.Integer as the return value means you are passing back an Object and the object reference can be null.
This is the initial database of the data source when you connect.
Edited for clarity:
If you have multiple databases in your SQL Server instance and you don't want to use the default database, you need some way to specify which one you are going to use.
Break out the LIKE
clauses into 2 separate statements, i.e.:
(fieldname1 LIKE '%this%' or fieldname1 LIKE '%that%' ) and something=else
I wrote this function:
public static String encode(@NonNull String uriString) {
if (TextUtils.isEmpty(uriString)) {
Assert.fail("Uri string cannot be empty!");
return uriString;
}
// getQueryParameterNames is not exist then cannot iterate on queries
if (Build.VERSION.SDK_INT < 11) {
return uriString;
}
// Check if uri has valid characters
// See https://tools.ietf.org/html/rfc3986
Pattern allowedUrlCharacters = Pattern.compile("([A-Za-z0-9_.~:/?\\#\\[\\]@!$&'()*+,;" +
"=-]|%[0-9a-fA-F]{2})+");
Matcher matcher = allowedUrlCharacters.matcher(uriString);
String validUri = null;
if (matcher.find()) {
validUri = matcher.group();
}
if (TextUtils.isEmpty(validUri) || uriString.length() == validUri.length()) {
return uriString;
}
// The uriString is not encoded. Then recreate the uri and encode it this time
Uri uri = Uri.parse(uriString);
Uri.Builder uriBuilder = new Uri.Builder()
.scheme(uri.getScheme())
.authority(uri.getAuthority());
for (String path : uri.getPathSegments()) {
uriBuilder.appendPath(path);
}
for (String key : uri.getQueryParameterNames()) {
uriBuilder.appendQueryParameter(key, uri.getQueryParameter(key));
}
String correctUrl = uriBuilder.build().toString();
return correctUrl;
}
Don't prematurely optimize. If you have no reason to believe there's a speed bottleneck caused by string concatenations then just stick with +
and +=
:
s = 'foo'
s += 'bar'
s += 'baz'
That said, if you're aiming for something like Java's StringBuilder, the canonical Python idiom is to add items to a list and then use str.join
to concatenate them all at the end:
l = []
l.append('foo')
l.append('bar')
l.append('baz')
s = ''.join(l)
Here is example for list of Objects
Map<String, Long> requirementCountMap = requirements.stream().collect(Collectors.groupingBy(Requirement::getRequirementType, Collectors.counting()));
you can use window.setInterval and time must to be define in miliseconds, in below case the function will call after every single second (1000 miliseconds)
<script>
var time = 3670;
window.setInterval(function(){
// Time calculations for days, hours, minutes and seconds
var h = Math.floor(time / 3600);
var m = Math.floor(time % 3600 / 60);
var s = Math.floor(time % 3600 % 60);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = h + "h "
+ m + "m " + s + "s ";
// If the count down is finished, write some text
if (time < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
time--;
}, 1000);
</script>
What you want to do is called "serialization". There are several ways of doing it, but if you don't need anything fancy I think using the standard Java object serialization would do just fine.
Perhaps you could use something like this?
package com.example;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Serializer {
public static byte[] serialize(Object obj) throws IOException {
try(ByteArrayOutputStream b = new ByteArrayOutputStream()){
try(ObjectOutputStream o = new ObjectOutputStream(b)){
o.writeObject(obj);
}
return b.toByteArray();
}
}
public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
try(ByteArrayInputStream b = new ByteArrayInputStream(bytes)){
try(ObjectInputStream o = new ObjectInputStream(b)){
return o.readObject();
}
}
}
}
There are several improvements to this that can be done. Not in the least the fact that you can only read/write one object per byte array, which might or might not be what you want.
Note that "Only objects that support the java.io.Serializable
interface can be written to streams" (see java.io.ObjectOutputStream
).
Since you might run into it, the continuous allocation and resizing of the java.io.ByteArrayOutputStream
might turn out to be quite the bottle neck. Depending on your threading model you might want to consider reusing some of the objects.
For serialization of objects that do not implement the Serializable
interface you either need to write your own serializer, for example using the read*/write* methods of java.io.DataOutputStream
and the get*/put* methods of java.nio.ByteBuffer
perhaps together with reflection, or pull in a third party dependency.
This site has a list and performance comparison of some serialization frameworks. Looking at the APIs it seems Kryo might fit what you need.
You can use the col element as specified in HTML 4.0 (link). It works in every browser. You can give it an ID or a class or an inline style. only caveat is that it affects the whole column across all rows. Example:
<table>
<col />
<col width="50" />
<col id="anId" />
<col class="whatever" />
<col style="border:1px solid #000;" />
<tbody>
<tr>
<td>One</td>
<td>Two</td>
<td>Three</td>
<td>Four</td>
<td>Five</td>
</tr>
</tbody>
</table>
SELECT CONVERT(NVARCHAR(20), GETDATE(), 23)
In shell, you don't put a $ in front of a variable you're assigning. You only use $IP when you're referring to the variable.
#!/bin/bash
IP=$(curl automation.whatismyip.com/n09230945.asp)
echo "$IP"
sed "s/IP/$IP/" nsupdate.txt | nsupdate
you can use ng-keydown , ng-keyup , ng-press such as this .
to triger a function :
<input type="text" ng-keypress="function()"/>
or if you have one condion such as when he press escape (27 is the key code for escape)
<form ng-keydown=" event.which=== 27?cancelSplit():0">
....
</form>
There is a visual studio plugin to support the java language: http://visualstudiogallery.msdn.microsoft.com/bc561769-36ff-4a40-9504-e266e8706f93
This problem bugs me for a long time since none of the work-around worked for me :(
But good news is, the following method works fine for my application.
The basic idea is to register a EventManager
in App.xmal.cs
to sniff PreviewMouseLeftButtonDownEvent
for all ComboBoxItem
, then trigger the SelectionChangedEvent
if the selecting item is the same as the selected item, i.e. the selection is performed without changing index.
In App.xmal.cs
:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
// raise selection change event even when there's no change in index
EventManager.RegisterClassHandler(typeof(ComboBoxItem), UIElement.PreviewMouseLeftButtonDownEvent,
new MouseButtonEventHandler(ComboBoxSelfSelection), true);
base.OnStartup(e);
}
private static void ComboBoxSelfSelection(object sender, MouseButtonEventArgs e)
{
var item = sender as ComboBoxItem;
if (item == null) return;
// find the combobox where the item resides
var comboBox = ItemsControl.ItemsControlFromItemContainer(item) as ComboBox;
if (comboBox == null) return;
// fire SelectionChangedEvent if two value are the same
if ((string)comboBox.SelectedValue == (string)item.Content)
{
comboBox.IsDropDownOpen = false;
comboBox.RaiseEvent(new SelectionChangedEventArgs(Selector.SelectionChangedEvent, new ListItem(), new ListItem()));
}
}
}
Then, for all combo boxes, register SelectionChangedEvent
in a normal way:
<ComboBox ItemsSource="{Binding BindList}"
SelectionChanged="YourSelectionChangedEventHandler"/>
Now, if two indices are different, nothing special but the ordinary event handling process; if two indices are the same, the Mouse Event on the item will first be handled, and thus trigger the SelectionChangedEvent
. In this way, both situations will trigger SelectionChangedEvent
:)
I just had the same problem with a cookie which was set to expire on "Browsing session end".
Unfortunately it did not so I played a bit with the settings of the browser.
Turned out that the feature that remembers the opened tabs when the browser is closed was the root of the problem. (The feature is named "On startup" - "Continue where I left off". At least on the current version of Chrome).
This also happens with Opera and Firefox.
Use the Application Verifier (AppVerifier) tool from Microsoft.
In my case I need to simulate memory no longer being available so I did the following in the tool:
After 2 minutes my program could no longer allocate new memory and I was able to see how everything was handled.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *substring(int i,int j,char *ch)
{
int n,k=0;
char *ch1;
ch1=(char*)malloc((j-i+1)*1);
n=j-i+1;
while(k<n)
{
ch1[k]=ch[i];
i++;k++;
}
return (char *)ch1;
}
int main()
{
int i=0,j=2;
char s[]="String";
char *test;
test=substring(i,j,s);
printf("%s",test);
free(test); //free the test
return 0;
}
This will compile fine without any warning
#include stdlib.h
test=substring(i,j,s)
; m
as it is unused char substring(int i,int j,char *ch)
or define it before main To make up for the daylight saving time (starting on March's last sunday until October's last sunday) I had to use the following formula:
=IF(
AND(
A2>=EOMONTH(DATE(YEAR(A2);3;1);0)-MOD(WEEKDAY(EOMONTH(DATE(YEAR(A2);3;1);0);11);7);
A2<=EOMONTH(DATE(YEAR(A2);10;1);0)-MOD(WEEKDAY(EOMONTH(DATE(YEAR(A2);10;1);0);11);7)
);
(A2-DATE(1970;1;1)-TIME(1;0;0))*24*60*60*1000;
(A2-DATE(1970;1;1))*24*60*60*1000
)
Quick explanation:
If the date ["A2"] is between March's last sunday and October's last sunday [third and fourth code lines], then I'll be subtracting one hour [-TIME(1;0;0)] to the date.
I've found a solution to solve this problem: use ${parent.relativePath}
<parent>
<artifactId>xxx</artifactId>
<groupId>xxx</groupId>
<version>1.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<build>
<filters>
<filter>${parent.relativePath}/src/main/filters/filter-${env}.properties</filter>
</filters>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
HTML are markup languages, basically they are set of tags like <html>
, <body>
, which is used to present a website using css, and javascript as a whole. All these, happen in the clients system or the user you will be browsing the website.
Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.
So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like php, jsp, asp.net etc.
Now, lets see a snippet of connection using MYSQLi Extension of PHP
$db = mysqli_connect('hostname','username','password','databasename');
This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:
<?php
$db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
<body>
<?php
$query = "SELECT * FROM `mytable`;";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
// Display your datas on the page
}
?>
</body>
</html>
In order to insert new data into the database, you can use phpMyAdmin
or write a INSERT
query and execute them.
manage_pages
permission (you may need the user_events
permission too, not sure)me/accounts
connection and copy your page's access_token
access_token
to the GET fieldsPAGE_ID/events
)base64 encode/decode example:
import base64
mystr = 'O João mordeu o cão!'
# Encode
mystr_encoded = base64.b64encode(mystr.encode('utf-8'))
# b'TyBKb8OjbyBtb3JkZXUgbyBjw6NvIQ=='
# Decode
mystr_encoded = base64.b64decode(mystr_encoded).decode('utf-8')
# 'O João mordeu o cão!'
I have used the technique said above, still I found that the time given in the Code:Blocks IDE was more or less similar to the result obtained-(may be it will differ by little micro seconds)..
If you want to enable unblur, you cannot just add the blur CSS to the body, you need to blur each visible child one level directly under the body and then remove the CSS to unblur. The reason is because of the "Cascade" in CSS, you cannot undo the cascading of the CSS blur effect for a child of the body. Also, to blur the body's background image you need to use the pseudo element :before
//HTML
<div id="fullscreen-popup" style="position:absolute;top:50%;left:50%;">
<div class="morph-button morph-button-overlay morph-button-fixed">
<button id="user-interface" type="button">MORE INFO</button>
<!--a id="user-interface" href="javascript:void(0)">popup</a-->
<div class="morph-content">
<div>
<div class="content-style-overlay">
<span class="icon icon-close">Close the overlay</span>
<h2>About Parsley</h2>
<p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
<p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
<p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
<p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
<p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
<p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
</div>
</div>
</div>
</div>
</div>
//CSS
/* Blur - doesn't work on IE */
.blur-on, .blur-element {
-webkit-filter: blur(10px);
-moz-filter: blur(10px);
-o-filter: blur(10px);
-ms-filter: blur(10px);
filter: blur(10px);
-webkit-transition: all 5s linear;
transition : all 5s linear;
-moz-transition : all 5s linear;
-webkit-transition: all 5s linear;
-o-transition : all 5s linear;
}
.blur-off {
-webkit-filter: blur(0px) !important;
-moz-filter : blur(0px) !important;
-o-filter : blur(0px) !important;
-ms-filter : blur(0px) !important;
filter : blur(0px) !important;
}
.blur-bgimage:before {
content: "";
position: absolute;
height: 20%; width: 20%;
background-size: cover;
background: inherit;
z-index: -1;
transform: scale(5);
transform-origin: top left;
filter: blur(2px);
-moz-transform: scale(5);
-moz-transform-origin: top left;
-moz-filter: blur(2px);
-webkit-transform: scale(5);
-webkit-transform-origin: top left;
-webkit-filter: blur(2px);
-o-transform: scale(5);
-o-transform-origin: top left;
-o-filter: blur(2px);
transition : all 5s linear;
-moz-transition : all 5s linear;
-webkit-transition: all 5s linear;
-o-transition : all 5s linear;
}
//Javascript
function blurBehindPopup() {
if(blurredElements.length == 0) {
for(var i=0; i < document.body.children.length; i++) {
var element = document.body.children[i];
if(element.id && element.id != 'fullscreen-popup' && element.isVisible == true) {
classie.addClass( element, 'blur-element' );
blurredElements.push(element);
}
}
} else {
for(var i=0; i < blurredElements.length; i++) {
classie.addClass( blurredElements[i], 'blur-element' );
}
}
}
function unblurBehindPopup() {
for(var i=0; i < blurredElements.length; i++) {
classie.removeClass( blurredElements[i], 'blur-element' );
}
}
Have you tried plugin called " Youtube Live Stream Auto Embed"
Its seems to be working. Check it once.
You should restart your Xampp or whatever server you're runnung, make sure sq
Yes, it is true that Abstraction and Encapsulation are about hiding.
Using only relevant details and hiding unnecessary data at Design Level is called Abstraction. (Like selecting only relevant properties for a class 'Car' to make it more abstract or general.)
Encapsulation is the hiding of data at Implementation Level. Like how to actually hide data from direct/external access. This is done by binding data and methods to a single entity/unit to prevent external access. Thus, encapsulation is also known as data hiding at implementation level.
My situation was a little different, I was trying to segue into a UINavigationController
, and what fixed it for me was getting the main queue portion.
For Objective-C:
dispatch_async(dispatch_get_main_queue(), ^{
[self performSegueWithIdentifier:@"SegueName" sender:self];
});
For Swift 3:
DispatchQueue.main.async { [weak self] in
self?.performSegue(withIdentifier: "SegueName", sender: self)
}
<%-- if you want to select value from drop-downlist here is jsp code. --%>
<body>
<form name="f1" method="get" action="#">
<select name="clr">
<option>Red</option>
<option>Blue</option>
<option>Green</option>
<option>Pink</option>
</select>
<input type="submit" name="submit" value="Select Color"/>
</form>
<%-- To display selected value from dropdown list. --%>
<%
String s=request.getParameter("clr");
if (s !=null)
{
out.println("Selected Color is : "+s);
}
%>
</body>
You need to add two new file one is index.html, copy and paste the below code and other is imageup.php which will upload your image
<form action="imageup.php" method="post" enctype="multipart/form-data">
<input type="file" name="banner" >
<input type="submit" value="submit">
</form>
imageup.php
<?php
$banner=$_FILES['banner']['name'];
$expbanner=explode('.',$banner);
$bannerexptype=$expbanner[1];
date_default_timezone_set('Australia/Melbourne');
$date = date('m/d/Yh:i:sa', time());
$rand=rand(10000,99999);
$encname=$date.$rand;
$bannername=md5($encname).'.'.$bannerexptype;
$bannerpath="uploads/banners/".$bannername;
move_uploaded_file($_FILES["banner"]["tmp_name"],$bannerpath);
?>
The above code will upload your image with encrypted name
If you want to copy the entire contents of a folder recursively into another folder, you can execute the following windows command from gulp:
xcopy /path/to/srcfolder /path/to/destfolder /s /e /y
The /y
option at the end is to suppress the overwrite confirmation message.
In Linux, you can execute the following command from gulp:
cp -R /path/to/srcfolder /path/to/destfolder
you can use gulp-exec or gulp-run plugin to execute system commands from gulp.
Related Links:
db.test.find( {"shapes.color": "red"}, {_id: 0})
Try the following snippet:
var mystring = 'this,is,an,example';
var splits = mystring.split(",");
alert(splits[0]); // output: this
Select Custom Structure in permalinks and add /%category%/%postname%/ after your domain. Adding "/" to the category base doesn't work, you have to add a period/dot. I wrote a tutorial for this here: remove category from URL tutorial
Use a Scanner
and pass in the delimiter and the original string:
result = new Scanner(result).useDelimiter("\n").next();
The following works for me very well,
<html>
<head>
<title>HTML Form</title>
</head>
<body>
<form>
<input type="button" value="ON" onclick="msg('ON')">
<input type="button" value="OFF" onclick="msg('OFF')">
</form>
<script>
function msg(x){
alert(x);
}
</script>
</body>
</html>
HashMap<Integer,String> hs1 = new HashMap<>();
hs1.put(1,"ram");
hs1.put(2,"sita");
hs1.put(3,"laxman");
hs1.put(4,"hanuman");
hs1.put(5,"geeta");
HashMap<Integer,String> hs2 = new HashMap<>();
hs2.put(5,"rat");
hs2.put(6,"lion");
hs2.put(7,"tiger");
hs2.put(8,"fish");
hs2.put(9,"hen");
HashMap<Integer,String> hs3 = new HashMap<>();//Map is which we add
hs3.putAll(hs1);
hs3.putAll(hs2);
System.out.println(" hs1 : " + hs1);
System.out.println(" hs2 : " + hs2);
System.out.println(" hs3 : " + hs3);
Duplicate items will not be added(that is duplicate keys) as when we will print hs3 we will get only one value for key 5 which will be last value added and it will be rat. **[Set has a property of not allowing the duplicate key but values can be duplicate]
As far as i remember, the documentation advises against using the menu icons from android.R.drawable directly and recommends copying them to your drawables folder. The main reason is that those icons and names can be subject to change and may not be available in future releases.
Warning: Because these resources can change between platform versions, you should not reference these icons using the Android platform resource IDs (i.e. menu icons under android.R.drawable). If you want to use any icons or other internal drawable resources, you should store a local copy of those icons or drawables in your application resources, then reference the local copy from your application code. In that way, you can maintain control over the appearance of your icons, even if the system's copy changes.
from: http://developer.android.com/guide/practices/ui_guidelines/icon_design_menu.html
The typed way to do this would be:
Number(true) // 1
Number(false) // 0
The Date
documentation states that :
The JavaScript date is based on a time value that is milliseconds since midnight January 1, 1970, UTC
Click on start button then on end button. It will show you the number of seconds between the 2 clicks.
The milliseconds diff is in variable timeDiff
. Play with it to find seconds/minutes/hours/ or what you need
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
startTime = new Date();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
endTime = new Date();_x000D_
var timeDiff = endTime - startTime; //in ms_x000D_
// strip the ms_x000D_
timeDiff /= 1000;_x000D_
_x000D_
// get seconds _x000D_
var seconds = Math.round(timeDiff);_x000D_
console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
_x000D_
<button onclick="end()">End</button>
_x000D_
OR another way of doing it for modern browser
Using performance.now()
which returns a value representing the time elapsed since the time origin. This value is a double with microseconds in the fractional.
The time origin is a standard time which is considered to be the beginning of the current document's lifetime.
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
startTime = performance.now();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
endTime = performance.now();_x000D_
var timeDiff = endTime - startTime; //in ms _x000D_
// strip the ms _x000D_
timeDiff /= 1000; _x000D_
_x000D_
// get seconds _x000D_
var seconds = Math.round(timeDiff);_x000D_
console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
<button onclick="end()">End</button>
_x000D_
Same as @axtavt, but you can use also the RequestDispatcher constant.
request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
Png files can handle transparency.
So you could use this question Save plot to image file instead of displaying it using Matplotlib so as to save you graph as a png
file.
And if you want to turn all white pixel transparent, there's this other question : Using PIL to make all white pixels transparent?
If you want to turn an entire area to transparent, then there's this question: And then use the PIL library like in this question Python PIL: how to make area transparent in PNG? so as to make your graph transparent.
This should do the trick.....
reset($array);
while (list($elementKey, $element) = each($array)) {
while (list($key, $value2) = each($element)) {
if($key == 'id' && $value == 'searched_value') {
unset($array[$elementKey]);
}
}
}
FOR ANDROID USERS:
You can use DateUtils.isToday(dateMilliseconds)
to check whether the given date is current day or not.
API reference: https://developer.android.com/reference/android/text/format/DateUtils.html#isToday(long)
Not really related to this answer, but I'd ditch git pull
, which just runs git fetch
followed by git merge
. You are doing three merges, which is going to make your Git run three fetch operations, when one fetch is all you will need. Hence:
git fetch origin # update all our origin/* remote-tracking branches
git checkout demo # if needed -- your example assumes you're on it
git merge origin/demo # if needed -- see below
git checkout master
git merge origin/master
git merge -X theirs demo # but see below
git push origin master # again, see below
The most interesting part here is git merge -X theirs
. As root545 noted, the -X
options are passed on to the merge strategy, and both the default recursive
strategy and the alternative resolve
strategy take -X ours
or -X theirs
(one or the other, but not both). To understand what they do, though, you need to know how Git finds, and treats, merge conflicts.
A merge conflict can occur within some file1 when the base version differs from both the current (also called local, HEAD, or --ours
) version and the other (also called remote or --theirs
) version of that same file. That is, the merge has identified three revisions (three commits): base, ours, and theirs. The "base" version is from the merge base between our commit and their commit, as found in the commit graph (for much more on this, see other StackOverflow postings). Git has then found two sets of changes: "what we did" and "what they did". These changes are (in general) found on a line-by-line, purely textual basis. Git has no real understanding of file contents; it is merely comparing each line of text.
These changes are what you see in git diff
output, and as always, they have context as well. It's possible that things we changed are on different lines from things they changed, so that the changes seem like they would not collide, but the context has also changed (e.g., due to our change being close to the top or bottom of the file, so that the file runs out in our version, but in theirs, they have also added more text at the top or bottom).
If the changes happen on different lines—for instance, we change color
to colour
on line 17 and they change fred
to barney
on line 71—then there is no conflict: Git simply takes both changes. If the changes happen on the same lines, but are identical changes, Git takes one copy of the change. Only if the changes are on the same lines, but are different changes, or that special case of interfering context, do you get a modify/modify conflict.
The -X ours
and -X theirs
options tell Git how to resolve this conflict, by picking just one of the two changes: ours, or theirs. Since you said you are merging demo
(theirs) into master
(ours) and want the changes from demo
, you would want -X theirs
.
Blindly applying -X
, however, is dangerous. Just because our changes did not conflict on a line-by-line basis does not mean our changes do not actually conflict! One classic example occurs in languages with variable declarations. The base version might declare an unused variable:
int i;
In our version, we delete the unused variable to make a compiler warning go away—and in their version, they add a loop some lines later, using i
as the loop counter. If we combine the two changes, the resulting code no longer compiles. The -X
option is no help here since the changes are on different lines.
If you have an automated test suite, the most important thing to do is to run the tests after merging. You can do this after committing, and fix things up later if needed; or you can do it before committing, by adding --no-commit
to the git merge
command. We'll leave the details for all of this to other postings.
1You can also get conflicts with respect to "file-wide" operations, e.g., perhaps we fix the spelling of a word in a file (so that we have a change), and they delete the entire file (so that they have a delete). Git will not resolve these conflicts on its own, regardless of -X
arguments.
There are three merges in both of our command sequences. The first is to bring origin/demo
into the local demo
(yours uses git pull
which, if your Git is very old, will fail to update origin/demo
but will produce the same end result). The second is to bring origin/master
into master
.
It's not clear to me who is updating demo
and/or master
. If you write your own code on your own demo
branch, and others are writing code and pushing it to the demo
branch on origin
, then this first-step merge can have conflicts, or produce a real merge. More often than not, it's better to use rebase, rather than merge, to combine work (admittedly, this is a matter of taste and opinion). If so, you might want to use git rebase
instead. On the other hand, if you never do any of your own commits on demo
, you don't even need a demo
branch. Alternatively, if you want to automate a lot of this, but be able to check carefully when there are commits that both you and others, made, you might want to use git merge --ff-only origin/demo
: this will fast-forward your demo
to match the updated origin/demo
if possible, and simply outright fail if not (at which point you can inspect the two sets of changes, and choose a real merge or a rebase as appropriate).
This same logic applies to master
, although you are doing the merge on master
, so you definitely do need a master
. It is, however, even likelier that you would want the merge to fail if it cannot be done as a fast-forward non-merge, so this probably also should be git merge --ff-only origin/master
.
Let's say that you never do your own commits on demo
. In this case we can ditch the name demo
entirely:
git fetch origin # update origin/*
git checkout master
git merge --ff-only origin/master || die "cannot fast-forward our master"
git merge -X theirs origin/demo || die "complex merge conflict"
git push origin master
If you are doing your own demo
branch commits, this is not helpful; you might as well keep the existing merge (but maybe add --ff-only
depending on what behavior you want), or switch it to doing a rebase. Note that all three methods may fail: merge may fail with a conflict, merge with --ff-only
may not be able to fast-forward, and rebase may fail with a conflict (rebase works by, in essence, cherry-picking commits, which uses the merge machinery and hence can get a merge conflict).
You may be interested in the output of
git symbolic-ref HEAD
In particular, depending on your needs and layout you may wish to do
basename $(git symbolic-ref HEAD)
or
git symbolic-ref HEAD | cut -d/ -f3-
and then again there is the .git/HEAD
file which may also be of interest for you.
First of all, from __future__ import print_function
needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print
as a function now. That's the whole point of from __future__ import print_function
; to bring the print
function from Python 3 into Python 2.6+.
from __future__ import print_function
import sys, os, time
for x in range(0,10):
print(x, sep=' ', end='') # No need for sep here, but okay :)
time.sleep(1)
__future__
statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:
A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.
The documentation also mentions that the only things that can precede a __future__
statement are the module docstring, comments, blank lines, and other future statements.
It's not exactly copy and paste but you can import data from Excel using Oracle SQL Developer.
Navigate to the table you want to import the data into and click on the Data
tab.
After clicking on the data tab you should notice a drop down that says Actions...
Click Actions...
and select the bottom option Import Data...
Then just follow the wizard to select the correct sheet, and columns that you want to import.
EDIT : To view the data tab :
SCHEMA
where your table is created.(Choose from the Connections tab on the left pane).SCHEMA
and choose SCHEMA BROWSER
.DATA
tab. Actions
and Import Data...
Is your link to another web page? If so, perhaps you could put the variable in the query string and set the session variable when the page being linked to is loaded.
So the link looks like this:
<a href="home.php?variable=value" name="home">home</a>
And the homge page would parse the query string and set the session variable.
int count = 0;
using (new SqlConnection connection = new SqlConnection("connectionString"))
{
sqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM table_name", connection);
connection.Open();
count = (int32)cmd.ExecuteScalar();
}
This is one of the way to add google site search to websites:
<form action="https://www.google.com/search" class="searchform" method="get" name="searchform" target="_blank">_x000D_
<input name="sitesearch" type="hidden" value="example.com">_x000D_
<input autocomplete="on" class="form-control search" name="q" placeholder="Search in example.com" required="required" type="text">_x000D_
<button class="button" type="submit">Search</button>_x000D_
</form>
_x000D_
I want to propose another way, how to solve limitation with IN operator.
For example we have following query
select *
from Users U
WHERE U.ID in (@ids)
We want to pass several IDs to filter users. Unfortunately it is not possible to do with C# in easy way. But I have fount workaround for this by using "string_split" function. We need to rewrite a bit our query to following.
declare @ids nvarchar(max) = '1,2,3'
SELECT *
FROM Users as U
CROSS APPLY string_split(@ids, ',') as UIDS
WHERE U.ID = UIDS.value
Now we can easily pass one parameter enumeration of values separated by comma.
I'm a little late to the party but I'll give my two cents. I just resolved this issue after spending longer than I'd like on it. The above solutions didn't work for me and here's why:
there was a network issue when maven was downloading the required repositories so I actually didn't have the right jars. adding a -U to a maven clean install went and got them for me. So if the above solutions aren't working try this:
Hope it works for you.
To do structural modification on the source of the stream, as Pshemo mentioned in his answer, one solution is to create a new instance of a Collection
like ArrayList
with the items inside your primary list; iterate over the new list, and do the operations on the primary list.
new ArrayList<>(users).stream().forEach(u -> users.remove(u));
Just a quick tip for someone who is in indecision regarding what library to use for lazy-loading images:
There are four basic ways.
DIY => Not the best solution but for a few images and if you want to go without the hassle of using others libraries
Volley's Lazy Loading library => From guys at android. It is nice and everything but is poorly documented and hence is a problem to use.
Picasso: A simple solution that just works, you can even specify the exact image size you want to bring in. It is very simple to use but might not be very "performant" for apps that has to deal with humongous amounts of images.
UIL: The best way to lazy load images. You can cache images(you need permission of course), initialize the loader once, then have your work done. The most mature asynchronous image loading library I have ever seen so far.
You want to use DateTimeOffset class.
var date = new DateTimeOffset(2009, 9, 1, 0, 0, 0, 0, new TimeSpan(0L));
var stringDate = date.ToString("u");
sorry I missed your original formatting with the miliseconds
var stringDate = date.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");
You can use DATEDIFF(it is a built-in function) and % (for scale calculation) and CONCAT for make result to only one column
select CONCAT('Month: ',MonthDiff,' Days: ' , DayDiff,' Minutes: ',MinuteDiff,' Seconds: ',SecondDiff) as T from
(SELECT DATEDIFF(MONTH, '2017-10-15 19:39:47' , '2017-12-31 23:59:59') % 12 as MonthDiff,
DATEDIFF(DAY, '2017-10-15 19:39:47' , '2017-12-31 23:59:59') % 30 as DayDiff,
DATEDIFF(HOUR, '2017-10-15 19:39:47' , '2017-12-31 23:59:59') % 24 as HourDiff,
DATEDIFF(MINUTE, '2017-10-15 19:39:47' , '2017-12-31 23:59:59') % 60 AS MinuteDiff,
DATEDIFF(SECOND, '2017-10-15 19:39:47' , '2017-12-31 23:59:59') % 60 AS SecondDiff) tbl
Does your cacerts.pem file hold a single certificate? Since it is a PEM, have a look at it (with a text editor), it should start with
-----BEGIN CERTIFICATE-----
and end with
-----END CERTIFICATE-----
Finally, to check it is not corrupted, get hold of openssl and print its details using
openssl x509 -in cacerts.pem -text
what about this simple inArray function:
Function isInArray(ByRef stringToBeFound As String, ByRef arr As Variant) As Boolean
For Each element In arr
If element = stringToBeFound Then
isInArray = True
Exit Function
End If
Next element
End Function
The way I think of it is like this: A unit test establishes that the code does what you intended the code to do (e.g. you wanted to add parameter a and b, you in fact add them, and don't subtract them), functional tests test that all of the code works together to get a correct result, so that what you intended the code to do in fact gets the right result in the system.
By far the easiest way to echo in powershell, is just create the string object and let the pipeline output it:
$filesizecounter = 8096
"filesizecounter : $filesizecounter"
Of course, you do give up some flexibility when not using the Write-* methods.
On XFCE, go to Applications -> Settings -> Settings editor - > xfwm4 -> easy_click(disable value)
Now you can Insert Cursor
with Alt + Click
I've also disabled L/R Workspace (ctrl + alt + L/R) settings in Settings -> Window manager -> Keyboard
This can be sought of a temporary solution.
Unicode has accepted U+20B9
as Indian rupee symbol soon all systems will update themselves
Here is a pitfall to avoid. In case you need to access your variable $name within a function, you need to say "global $name;" at the beginning of that function. You need to repeat this for each function in the same file.
include('front.inc');
global $name;
function foo() {
echo $name;
}
function bar() {
echo $name;
}
foo();
bar();
will only show errors. The correct way to do that would be:
include('front.inc');
function foo() {
global $name;
echo $name;
}
function bar() {
global $name;
echo $name;
}
foo();
bar();
Install Ruby-sass using below command
sudo apt-get -y update
sudo apt-get -y install ruby-full
sudo apt install ruby-sass
gem install bundler
Example
sass SCSS_FILE_PATH:CSS_FILE_PATH;
e.g sass mda/at-md-black.scss:css/at-md-black.css;
If you are in a directory or folder where the script file is available then simply change the file permission in executable mode by doing
chmod +x your_filename.sh
After that you will run the script by using the following command.
$ sudo ./your_filename.sh
Above the "." represent the current directory. Note! If you are not in the directory where the bash script file is present then you change the directory where the file is located by using
cd Directory_name/write the complete path
command. Otherwise your script can not run.
This code might work for non-.NET Core MVC controllers:
this.HttpContext.Response.StatusCode = 418; // I'm a teapot
return Json(new { status = "mer" }, JsonRequestBehavior.AllowGet);
If you do not need to retrieve all the row and want to avoid to make a double query, you can probably try something like that:
using (var sqlCon = new SqlConnection("Server=127.0.0.1;Database=MyDb;User Id=Me;Password=glop;"))
{
sqlCon.Open();
var com = sqlCon.CreateCommand();
com.CommandText = "select * from BigTable";
using (var reader = com.ExecuteReader())
{
//here you retrieve what you need
}
com.CommandText = "select @@ROWCOUNT";
var totalRow = com.ExecuteScalar();
sqlCon.Close();
}
You may have to add a transaction not sure if reusing the same command will automatically add a transaction on it...
As yum install php-mbstring
then httpd -k restart
didn't do it for me, I think these options should be compiled, as documented here:
Now, configure and build PHP. This is where you customize PHP with various options, like which extensions will be enabled. Run ./configure --help for a list of available options. In our example we'll do a simple configure with Apache 2 and MySQL support.
If you built Apache from source, as described above, the below example will match your path for apxs, but if you installed Apache some other way, you'll need to adjust the path to apxs accordingly. Note that some distros may rename apxs to apxs2.
cd ../php-NN ./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql --enable-mbstring make make install
If you decide to change your configure options after installation, you'll need to re-run the configure, make, and make install steps. You only need to restart apache for the new module to take effect. A recompile of Apache is not needed.
Note that unless told otherwise, 'make install' will also install PEAR, various PHP tools such as phpize, install the PHP CLI, and more.
Though this page says it's optional:
--enable-mbstring Allows multibyte character string support. This is optional, as slower custom code will be used if not available.
I found useful npm package https://www.npmjs.com/package/element-resize-detector
An optimized cross-browser resize listener for elements.
Can use it with React component or functional component(Specially useful for react hooks)
Inside of a for-loop block, you can access some special variables including loop.index
--but no loop.counter
. From the official docs:
Variable Description
loop.index The current iteration of the loop. (1 indexed)
loop.index0 The current iteration of the loop. (0 indexed)
loop.revindex The number of iterations from the end of the loop (1 indexed)
loop.revindex0 The number of iterations from the end of the loop (0 indexed)
loop.first True if first iteration.
loop.last True if last iteration.
loop.length The number of items in the sequence.
loop.cycle A helper function to cycle between a list of sequences. See the explanation below.
loop.depth Indicates how deep in a recursive loop the rendering currently is. Starts at level 1
loop.depth0 Indicates how deep in a recursive loop the rendering currently is. Starts at level 0
loop.previtem The item from the previous iteration of the loop. Undefined during the first iteration.
loop.nextitem The item from the following iteration of the loop. Undefined during the last iteration.
loop.changed(*val) True if previously called with a different value (or not called at all).
That's what ln
is documented to do when the target already exists and is a directory. If you want /etc/nginx
to be a symlink rather than contain a symlink, you had better not create it as a directory first!
Scott Meyers gives a nice example:
class GameCharacter;
int defaultHealthCalc(const GameCharacter& gc);
class GameCharacter
{
public:
typedef std::function<int (const GameCharacter&)> HealthCalcFunc;
explicit GameCharacter(HealthCalcFunc hcf = defaultHealthCalc)
: healthFunc(hcf)
{ }
int healthValue() const { return healthFunc(*this); }
private:
HealthCalcFunc healthFunc;
};
I think the example says it all.
std::function<>
is the "modern" way of writing C++ callbacks.
I can't give you graphics, but maybe I can give a clear explanation.
Suppose we have an information channel, such as a light that flashes once every day either red or green. How much information does it convey? The first guess might be one bit per day. But what if we add blue, so that the sender has three options? We would like to have a measure of information that can handle things other than powers of two, but still be additive (the way that multiplying the number of possible messages by two adds one bit). We could do this by taking log2(number of possible messages), but it turns out there's a more general way.
Suppose we're back to red/green, but the red bulb has burned out (this is common knowledge) so that the lamp must always flash green. The channel is now useless, we know what the next flash will be so the flashes convey no information, no news. Now we repair the bulb but impose a rule that the red bulb may not flash twice in a row. When the lamp flashes red, we know what the next flash will be. If you try to send a bit stream by this channel, you'll find that you must encode it with more flashes than you have bits (50% more, in fact). And if you want to describe a sequence of flashes, you can do so with fewer bits. The same applies if each flash is independent (context-free), but green flashes are more common than red: the more skewed the probability the fewer bits you need to describe the sequence, and the less information it contains, all the way to the all-green, bulb-burnt-out limit.
It turns out there's a way to measure the amount of information in a signal, based on the the probabilities of the different symbols. If the probability of receiving symbol xi is pi, then consider the quantity
-log pi
The smaller pi, the larger this value. If xi becomes twice as unlikely, this value increases by a fixed amount (log(2)). This should remind you of adding one bit to a message.
If we don't know what the symbol will be (but we know the probabilities) then we can calculate the average of this value, how much we will get, by summing over the different possibilities:
I = -Σ pi log(pi)
This is the information content in one flash.
Red bulb burnt out: pred = 0, pgreen=1, I = -(0 + 0) = 0 Red and green equiprobable: pred = 1/2, pgreen = 1/2, I = -(2 * 1/2 * log(1/2)) = log(2) Three colors, equiprobable: pi=1/3, I = -(3 * 1/3 * log(1/3)) = log(3) Green and red, green twice as likely: pred=1/3, pgreen=2/3, I = -(1/3 log(1/3) + 2/3 log(2/3)) = log(3) - 2/3 log(2)
This is the information content, or entropy, of the message. It is maximal when the different symbols are equiprobable. If you're a physicist you use the natural log, if you're a computer scientist you use log2 and get bits.
You can use CountIf
. Put the following code in B1 and drag down the whole column
=COUNTIF(A:A,A1)
It will look like this:
Functions are easy to call inside a select loop, but they don't let you run inserts, updates, deletes, etc. They are only useful for query operations. You need a stored procedure to manipulate the data.
So, the real answer to this question is that you must iterate through the results of a select statement via a "cursor" and call the procedure from within that loop. Here's an example:
DECLARE @myId int;
DECLARE @myName nvarchar(60);
DECLARE myCursor CURSOR FORWARD_ONLY FOR
SELECT Id, Name FROM SomeTable;
OPEN myCursor;
FETCH NEXT FROM myCursor INTO @myId, @myName;
WHILE @@FETCH_STATUS = 0 BEGIN
EXECUTE dbo.myCustomProcedure @myId, @myName;
FETCH NEXT FROM myCursor INTO @myId, @myName;
END;
CLOSE myCursor;
DEALLOCATE myCursor;
Note that @@FETCH_STATUS
is a standard variable which gets updated for you. The rest of the object names here are custom.
An example of an associated full GC also shows the collectors used for the old and permanent generations:
3.757: [Full GC [PSYoungGen: 2672K->0K(35584K)]
[ParOldGen: 3225K->5735K(43712K)] 5898K->5735K(79296K)
[PSPermGen: 13533K->13516K(27584K)], 0.0860402 secs]
Finally, breaking down one line of your example log output:
8109.128: [GC [PSYoungGen: 109884K->14201K(139904K)] 691015K->595332K(1119040K), 0.0454530 secs]
First execute this
sudo apt-get install gcc binutils make linux-source
Then run again
/usr/bin/vmware-config-tools.pl
This is all you need to do. Now your system has the gcc make and the linux kernel sources.
I found that the Swift 3 posted by Evgenii Kanvets does not uniformly scale the image.
Here is my Swift 4 version of the function that does not squish the image:
static func resizedCroppedImage(image: UIImage, newSize:CGSize) -> UIImage? {
// This function returns a newImage, based on image
// - image is scaled uniformaly to fit into a rect of size newSize
// - if the newSize rect is of a different aspect ratio from the source image
// the new image is cropped to be in the center of the source image
// (the excess source image is removed)
var ratio: CGFloat = 0
var delta: CGFloat = 0
var drawRect = CGRect()
if newSize.width > newSize.height {
ratio = newSize.width / image.size.width
delta = (ratio * image.size.height) - newSize.height
drawRect = CGRect(x: 0, y: -delta / 2, width: newSize.width, height: newSize.height + delta)
} else {
ratio = newSize.height / image.size.height
delta = (ratio * image.size.width) - newSize.width
drawRect = CGRect(x: -delta / 2, y: 0, width: newSize.width + delta, height: newSize.height)
}
UIGraphicsBeginImageContextWithOptions(newSize, true, 0.0)
image.draw(in: drawRect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
The new command to flush the privileges is:
FLUSH PRIVILEGES
The old command FLUSH ALL PRIVILEGES
does not work any more.
You will get an error that looks like that:
MariaDB [(none)]> FLUSH ALL PRIVILEGES;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ALL PRIVILEGES' at line 1
Hope this helps :)
The answers above are incorrect, they will all run weather or not the submission is successful... You need to write an error component that will receive any errors then check if there are errors in state, if there are not then clear the form....
use .then()
example:
const onSubmit = e => {
e.preventDefault();
const fd = new FormData();
fd.append("ticketType", ticketType);
fd.append("ticketSubject", ticketSubject);
fd.append("ticketDescription", ticketDescription);
fd.append("itHelpType", itHelpType);
fd.append("ticketPriority", ticketPriority);
fd.append("ticketAttachments", ticketAttachments);
newTicketITTicket(fd).then(()=>{
setTicketData({
ticketType: "IT",
ticketSubject: "",
ticketDescription: "",
itHelpType: "",
ticketPriority: ""
})
})
};
@section
is for defining a content are override from a shared view. Basically, it is a way for you to adjust your shared view (similar to a Master Page in Web Forms).
You might find Scott Gu's write up on this very interesting.
Edit: Based on additional question clarification
The @RenderSection
syntax goes into the Shared View, such as:
<div id="sidebar">
@RenderSection("Sidebar", required: false)
</div>
This would then be placed in your view with @Section
syntax:
@section Sidebar{
<!-- Content Here -->
}
In MVC3+ you can either define the Layout file to be used for the view directly or you can have a default view for all views.
Common view settings can be set in _ViewStart.cshtml which defines the default layout view similar to this:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
You can also set the Shared View to use directly in the file, such as index.cshtml directly as shown in this snippet.
@{
ViewBag.Title = "Corporate Homepage";
ViewBag.BodyID = "page-home";
Layout = "~/Views/Shared/_Layout2.cshtml";
}
There are a variety of ways you can adjust this setting with a few more mentioned in this SO answer.
I had this problem and
dumpbin /exports mydll.dll
and
depends mydll.dll
showed 'DllRegisterServer'.
The problem was that there was another DLL in the system that had the same name. After renaming mydll the registration succeeded.
You can use the following command to clear out ALL variables. Be careful because it you cannot get your variables back.
rm(list=ls(all=TRUE))
This worked for me:
location / {
# redirect all HTTP traffic to localhost:8080
proxy_pass http://localhost:8080;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# WebSocket support
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
-- borrowed from: https://github.com/nicokaiser/nginx-websocket-proxy/blob/df67cd92f71bfcb513b343beaa89cb33ab09fb05/simple-wss.conf
To expand on the above and make a quick reference:
ALTER USER username WITH SUPERUSER;
ALTER USER username WITH NOSUPERUSER;
ALTER USER username CREATEDB;
You can also use CREATEROLE
and CREATEUSER
to allow a user privileges without making them a superuser.
You can apply only to certain attribute by doing:
input[type="checkbox"] {...}
It explains it here.
I just managed to make it work again. It makes not much sense but it worked:
I'll investigate further later but the method I called with hangfire receives a DBContext and that is the possible cause.
for using this, you can create a Repository for example this one:
Member findByEmail(String email);
List<Member> findByDate(Date date);
// custom query example and return a member
@Query("select m from Member m where m.username = :username and m.password=:password")
Member findByUsernameAndPassword(@Param("username") String username, @Param("password") String password);
If this don't work
My 2 cents: the same code works even if iOS:
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
showIP();
}
void showIP()
{
struct ifaddrs *ifaddr, *ifa;
int family, s;
char host[NI_MAXHOST];
if (getifaddrs(&ifaddr) == -1)
{
perror("getifaddrs");
exit(EXIT_FAILURE);
}
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
{
if (ifa->ifa_addr == NULL)
continue;
s=getnameinfo(ifa->ifa_addr,sizeof(struct sockaddr_in),host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
if( /*(strcmp(ifa->ifa_name,"wlan0")==0)&&( */ ifa->ifa_addr->sa_family==AF_INET) // )
{
if (s != 0)
{
printf("getnameinfo() failed: %s\n", gai_strerror(s));
exit(EXIT_FAILURE);
}
printf("\tInterface : <%s>\n",ifa->ifa_name );
printf("\t Address : <%s>\n", host);
}
}
freeifaddrs(ifaddr);
}
@end
I simply removed the test against wlan0 to see data. ps You can remove "family"
Im not very familiar with the Android sdk, but it seems that the android-sdk
comes with the BouncyCastle
provider already added to the security.
What you will have to do in the PC environment is just add it manually,
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
if you have access to the policy
file, just add an entry like:
security.provider.5=org.bouncycastle.jce.provider.BouncyCastleProvider
Notice the .5
it is equal to a sequential number of the already added providers.
I was stuck with the same problem, but I found a solution. I did it the same way as this blog did.
Of course this was Java, I've translated it to Python:
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.dir",getcwd())
fp.set_preference("browser.helperApps.neverAsk.saveToDisk","text/csv")
browser = webdriver.Firefox(firefox_profile=fp)
In my example it was a CSV file. But when you need more, there are stored in the ~/.mozilla/$USER_PROFILE/mimeTypes.rdf
copy your war file to /tmp now extract the contents:
cp warfile.war /tmp
cd /tmp
unzip warfile.war
cd WEB-INF
nano web.xml (or vim or any editor you want to use)
cd ..
zip -r -u warfile.war WEB-INF
now you have in /tmp/warfile.war your file updated.
Instead of comparison methods you may want to just define several types of "Comparator" subclasses inside the Person class. That way you can pass them into standard Collections sorting methods.
See https://polarssl.org/kb/cryptography/asn1-key-structures-in-der-and-pem (search the page for "BEGIN RSA PRIVATE KEY") (archive link for posterity, just in case).
BEGIN RSA PRIVATE KEY
is PKCS#1 and is just an RSA key. It is essentially just the key object from PKCS#8, but without the version or algorithm identifier in front. BEGIN PRIVATE KEY
is PKCS#8 and indicates that the key type is included in the key data itself. From the link:
The unencrypted PKCS#8 encoded data starts and ends with the tags:
-----BEGIN PRIVATE KEY----- BASE64 ENCODED DATA -----END PRIVATE KEY-----
Within the base64 encoded data the following DER structure is present:
PrivateKeyInfo ::= SEQUENCE { version Version, algorithm AlgorithmIdentifier, PrivateKey BIT STRING } AlgorithmIdentifier ::= SEQUENCE { algorithm OBJECT IDENTIFIER, parameters ANY DEFINED BY algorithm OPTIONAL }
So for an RSA private key, the OID is 1.2.840.113549.1.1.1 and there is a RSAPrivateKey as the PrivateKey key data bitstring.
As opposed to BEGIN RSA PRIVATE KEY
, which always specifies an RSA key and therefore doesn't include a key type OID. BEGIN RSA PRIVATE KEY
is PKCS#1
:
RSA Private Key file (PKCS#1)
The RSA private key PEM file is specific for RSA keys.
It starts and ends with the tags:
-----BEGIN RSA PRIVATE KEY----- BASE64 ENCODED DATA -----END RSA PRIVATE KEY-----
Within the base64 encoded data the following DER structure is present:
RSAPrivateKey ::= SEQUENCE { version Version, modulus INTEGER, -- n publicExponent INTEGER, -- e privateExponent INTEGER, -- d prime1 INTEGER, -- p prime2 INTEGER, -- q exponent1 INTEGER, -- d mod (p-1) exponent2 INTEGER, -- d mod (q-1) coefficient INTEGER, -- (inverse of q) mod p otherPrimeInfos OtherPrimeInfos OPTIONAL }
out.write(c.toString());
out.newLine();
here is a simple solution, I hope it works
EDIT: I was using "\n" which was obviously not recommended approach, modified answer.