Use Enum.GetName
From the above link...
using System;
public class GetNameTest {
enum Colors { Red, Green, Blue, Yellow };
enum Styles { Plaid, Striped, Tartan, Corduroy };
public static void Main() {
Console.WriteLine("The 4th value of the Colors Enum is {0}", Enum.GetName(typeof(Colors), 3));
Console.WriteLine("The 4th value of the Styles Enum is {0}", Enum.GetName(typeof(Styles), 3));
}
}
// The example displays the following output:
// The 4th value of the Colors Enum is Yellow
// The 4th value of the Styles Enum is Corduroy
Well, container objects' __str__
methods will use repr
on their contents, not str
. So you could use __repr__
instead of __str__
, seeing as you're using an ID as the result.
If you have an Asp.Net web application, you can also set it in the web.config
so that it is the same throughout the whole web application
<system.web>
...
<globalization
requestEncoding="utf-8"
responseEncoding="utf-8"
culture="en-GB"
uiCulture="en-GB"
enableClientBasedCulture="false"/>
...
</system.web>
if (HttpContext.Current.Session["emp_num"] != null)
{
// code if session is not null
}
When the JVM
tries to run your application, it calls your main method statically; something like this:
LinkedList.main();
That means there is no instance of your LinkedList
class. In order to call your toString()
method, you can create a new instance of your LinkedList
class.
So the body of your main
method should be like this:
public static void main(String[] args){
// creating an instance of LinkedList class
LinkedList ll = new LinkedList();
// adding some data to the list
ll.insertFront(1);
ll.insertFront(2);
ll.insertFront(3);
ll.insertBack(4);
System.out.println(ll.toString());
}
You still have an option to implement in your enum this:
public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name){...}
This is a known bug under MinGW. Relevant Bugzilla. In the comments section you can get a patch to make it work with MinGW.
This issue has been fixed in MinGW-w64 distros higher than GCC 4.8.0 provided by the MinGW-w64 project. Despite the name, the project provides toolchains for 32-bit along with 64-bit. The Nuwen MinGW distro also solves this issue.
Or in case you just need the value of the first seleted sell (or just one selected cell if one is selected)
TextBox1.Text = SelectedCells[0].Value.ToString();
In Eclipse,
Go to your class,
Right click->source->Generate toString()
;
It will override the toString()
method and will print the object of that class.
1.
JSON.stringify(o);
Item: {"a":"1", "b":"2"}
2.
var o = {a:1, b:2};
var b=[]; Object.keys(o).forEach(function(k){b.push(k+":"+o[k]);});
b="{"+b.join(', ')+"}";
console.log('Item: ' + b);
Item: {a:1, b:2}
Use Object#toString()
.
String string = map.toString();
That's after all also what System.out.println(object)
does under the hoods. The format for maps is described in AbstractMap#toString()
.
Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's
entrySet
view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as byString.valueOf(Object)
.
[Ljava.lang.Object;
is the name for Object[].class
, the java.lang.Class
representing the class of array of Object
.
The naming scheme is documented in Class.getName()
:
If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by the Java Language Specification (§13.1).
If this class object represents a primitive type or
void
, then the name returned is the Java language keyword corresponding to the primitive type orvoid
.If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more
'['
characters representing the depth of the array nesting. The encoding of element type names is as follows:Element Type Encoding boolean Z byte B char C double D float F int I long J short S class or interface Lclassname;
Yours is the last on that list. Here are some examples:
// xxxxx varies
System.out.println(new int[0][0][7]); // [[[I@xxxxx
System.out.println(new String[4][2]); // [[Ljava.lang.String;@xxxxx
System.out.println(new boolean[256]); // [Z@xxxxx
The reason why the toString()
method on arrays returns String
in this format is because arrays do not @Override
the method inherited from Object
, which is specified as follows:
The
toString
method for classObject
returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:getClass().getName() + '@' + Integer.toHexString(hashCode())
Note: you can not rely on the toString()
of any arbitrary object to follow the above specification, since they can (and usually do) @Override
it to return something else. The more reliable way of inspecting the type of an arbitrary object is to invoke getClass()
on it (a final
method inherited from Object
) and then reflecting on the returned Class
object. Ideally, though, the API should've been designed such that reflection is not necessary (see Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection).
toString
for arraysjava.util.Arrays
provides toString
overloads for primitive arrays and Object[]
. There is also deepToString
that you may want to use for nested arrays.
Here are some examples:
int[] nums = { 1, 2, 3 };
System.out.println(nums);
// [I@xxxxx
System.out.println(Arrays.toString(nums));
// [1, 2, 3]
int[][] table = {
{ 1, },
{ 2, 3, },
{ 4, 5, 6, },
};
System.out.println(Arrays.toString(table));
// [[I@xxxxx, [I@yyyyy, [I@zzzzz]
System.out.println(Arrays.deepToString(table));
// [[1], [2, 3], [4, 5, 6]]
There are also Arrays.equals
and Arrays.deepEquals
that perform array equality comparison by their elements, among many other array-related utility methods.
The correct way is actually:
webBrowser1.DocumentText
You can use java.util.Arrays:
String res = Arrays.toString(array);
System.out.println(res);
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
I prefer something like the following:
type StringRef []byte
func (s StringRef) String() string {
return string(s[:])
}
…
// rather silly example, but ...
fmt.Printf("foo=%s\n",StringRef("bar"))
My understanding is that you have to create a partial class to "extend" your model and add a property that is readonly that can utilize the rest of the class's properties.
public partial class Contact{
public string ContactIdString
{
get{
return this.ContactId.ToString();
}
}
}
Then
var items = from c in contacts
select new ListItem
{
Value = c.ContactIdString,
Text = c.Name
};
ToString("X2") prints the input in Hexadecimal
Convert.ToString(strName)
will handle null-able values and strName.Tostring()
will not handle null value and throw an exception.
So It is better to use Convert.ToString()
then .ToString();
public static String getStackTrace(Throwable t) {
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
return sw.toString();
}
std::string stringify(double x)
{
std::ostringstream o;
if (!(o << x))
throw BadConversion("stringify(double)");
return o.str();
}
C++ FAQ: http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.1
I was trying to clone a repo and was facing this issue, I tried removing all git related credentials from windows credentials manager
after that while trying to clone git was asking me for my credentials and failing with error invalid username or password
. This was happening because the repo I was trying to clone was under an organization on github and that organization had two factor auth enabled and git bash probably do not know how to handle 2fa. So I generated a token from https://github.com/settings/tokens and used the github token instead of password while trying to clone the repo and that worked.
Expand the SQL Server Agent node and right click the Jobs node in SQL Server Agent and select 'New Job'
In the 'New Job'
window enter the name of the job and a description on the 'General'
tab.
Select 'Steps'
on the left hand side of the window and click 'New'
at the bottom.
In the 'Steps'
window enter a step name and select the database you want the query to run against.
Paste in the T-SQL command you want to run into the Command window and click 'OK'
.
Click on the 'Schedule'
menu on the left of the New Job window and enter the schedule information (e.g. daily and a time).
Click 'OK'
- and that should be it.
(There are of course other options you can add - but I would say that is the bare minimum you need to get a job set up and scheduled)
Easiest solution:
kill $(lsof -ti:3000,3001,8080)
For single port:
kill $(lsof -ti:3000)
#3000 is the port to be freed
Kill multiple ports with single line command:
kill $(lsof -ti:3000,3001)
#here multiple ports 3000 and 3001 are the ports to be freed
lsof -ti:3000
82500 (Process ID)
lsof -ti:3001
82499
lsof -ti:3001,3000
82499 82500
kill $(lsof -ti:3001,3000)
Terminates both 82499 and 82500 processes in a single command.
For using this in package.json
scripts:
"scripts": { "start": "kill $(lsof -ti:3000,3001) && npm start" }
It seems as if Android Studio is missing some features Eclipse has (which is surprising considering the choice to make Android Studio official IDE).
Eclipse had the ability to export zip files which could be sent over email for example. If you zip the folder from your workspace, and try to send it over Gmail for example, Gmail will refuse because the folder contains executable. Obviously you can delete files but that is inefficient if you do that frequently going back and forth from work.
Here's a solution though: You can use source control. Android Studio supports that. Your code will be stored online. A git will do the trick. Look under "VCS" in the top menu in Android Studio. It has many other benefits as well. One of the downsides though, is that if you use GitHub for free, your code is open source and everyone can see it.
We can use an optional merger function also in case of same key collision. For example, If two or more persons have the same getLast() value, we can specify how to merge the values. If we not do this, we could get IllegalStateException. Here is the example to achieve this...
Map<String, Person> map =
roster
.stream()
.collect(
Collectors.toMap(p -> p.getLast(),
p -> p,
(person1, person2) -> person1+";"+person2)
);
@shrx I've succeeded to unpack the BSD.pkg (part of the Yosemite installer) by using "pbzx" command.
pbzx <pkg> | cpio -idmu
The "pbzx" command can be downloaded from the following link:
Things have moved on a bit since this thread started.
Now, you could use
string.Concat(s.TakeWhile((c) => c != '-'));
Necromancing, just in case all the links go dark:
Add a group to your report
Also, be advised to set the sort order of the group expression here, so the tabs will be alphabetically sorted (or however you want it sorted).
Set the page break in the group properties
Now you need to set the PageName
of the Tablix Member (group), NOT the PageName
of the Tablix itselfs.
If you got the right object, if will say "Tablix Member" (Tablix-Element in German) in the title box of the properties grid. If it's the wrong object, it will say only "table/tablix" (without member) in the property grid's title box.
Note: If you get the tablix instead of the tablix member, it will put the same tab name in every tab, followed by a (tabNum)
! If that happens, you now know what the problem is.
It means "a python object", i.e. not one of the builtin scalar types supported by numpy.
np.array([object()]).dtype
=> dtype('O')
there you go
$date = "04-15-2013";
$date1 = str_replace('-', '/', $date);
$tomorrow = date('m-d-Y',strtotime($date1 . "+1 days"));
echo $tomorrow;
this will output
04-16-2013
As an alternative, if there's not a specific reason to use Math.random()
, use Random.nextInt()
:
import java.util.Random;
Random rnd = new Random();
int abc = rnd.nextInt(100); // +1 if you want 1-100, otherwise will be 0-99.
I'm using a simplyfied version (just using position relative) based on @SimonEast answer:
li:before {
content: "\e080";
font-family: 'Glyphicons Halflings';
font-size: 9px;
position: relative;
margin-right: 10px;
top: 3px;
color: #ccc;
}
In case anyone comes across this article looking for what I was looking for, I found examples at
How to visualize scalar 2D data with Matplotlib?
and
http://mri.brechmos.org/2009/07/automatically-update-a-figure-in-a-loop (on web.archive.org)
then modified them to use imshow with an input stack of frames, instead of generating and using contours on the fly.
Starting with a 3D array of images of shape (nBins, nBins, nBins), called frames
.
def animate_frames(frames):
nBins = frames.shape[0]
frame = frames[0]
tempCS1 = plt.imshow(frame, cmap=plt.cm.gray)
for k in range(nBins):
frame = frames[k]
tempCS1 = plt.imshow(frame, cmap=plt.cm.gray)
del tempCS1
fig.canvas.draw()
#time.sleep(1e-2) #unnecessary, but useful
fig.clf()
fig = plt.figure()
ax = fig.add_subplot(111)
win = fig.canvas.manager.window
fig.canvas.manager.window.after(100, animate_frames, frames)
I also found a much simpler way to go about this whole process, albeit less robust:
fig = plt.figure()
for k in range(nBins):
plt.clf()
plt.imshow(frames[k],cmap=plt.cm.gray)
fig.canvas.draw()
time.sleep(1e-6) #unnecessary, but useful
Note that both of these only seem to work with ipython --pylab=tk
, a.k.a.backend = TkAgg
Thank you for the help with everything.
Let's suppose that you have a system running Ubuntu 16.04, 16.10, or 17.04, and you want Python 3.6 to be the default Python.
If you're using Ubuntu 16.04 LTS, you'll need to use a PPA:
sudo add-apt-repository ppa:jonathonf/python-3.6 # (only for 16.04 LTS)
Then, run the following (this works out-of-the-box on 16.10 and 17.04):
sudo apt update
sudo apt install python3.6
sudo apt install python3.6-dev
sudo apt install python3.6-venv
wget https://bootstrap.pypa.io/get-pip.py
sudo python3.6 get-pip.py
sudo ln -s /usr/bin/python3.6 /usr/local/bin/python3
sudo ln -s /usr/local/bin/pip /usr/local/bin/pip3
# Do this only if you want python3 to be the default Python
# instead of python2 (may be dangerous, esp. before 2020):
# sudo ln -s /usr/bin/python3.6 /usr/local/bin/python
When you have completed all of the above, each of the following shell commands should indicate Python 3.6.1
(or a more recent version of Python 3.6):
python --version # (this will reflect your choice, see above)
python3 --version
$(head -1 `which pip` | tail -c +3) --version
$(head -1 `which pip3` | tail -c +3) --version
Check out angular-ui, specifically, route checking: http://angular-ui.github.io/ui-utils/
You can use simple jQuery jPut plugin
http://plugins.jquery.com/jput/
<script>
$(document).ready(function(){
var json = [{"name": "name1","email":"[email protected]"},{"name": "name2","link":"[email protected]"}];
//while running this code the template will be appended in your div with json data
$("#tbody").jPut({
jsonData:json,
//ajax_url:"youfile.json", if you want to call from a json file
name:"tbody_template",
});
});
</script>
<table jput="t_template">
<tbody jput="tbody_template">
<tr>
<td>{{name}}</td>
<td>{{email}}</td>
</tr>
</tbody>
</table>
<table>
<tbody id="tbody">
</tbody>
</table>
Here's a shell script to remove a tagged (named) image and it's containers. Save as docker-rmi and run using 'docker-rmi my-image-name'
#!/bin/bash
IMAGE=$1
if [ "$IMAGE" == "" ] ; then
echo "Missing image argument"
exit 2
fi
docker ps -qa -f "ancestor=$IMAGE" | xargs docker rm
docker rmi $IMAGE
I see what you are trying to ask and I think this is the simplest answer to what you are looking for, given you might not know how many key pairs your are being sent.
Simple Key Pair JSON structure
var data = {
'XXXXXX' : '100.0',
'YYYYYYY' : '200.0',
'ZZZZZZZ' : '500.0',
}
Usage JavaScript code to access the key pairs
for (var key in data)
{ if (!data.hasOwnProperty(key))
{ continue; }
console.log(key + ' -> ' + data[key]);
};
Console output should look like this
XXXXXX -> 100.0
YYYYYYY -> 200.0
ZZZZZZZ -> 500.0
Here is a JSFiddle to show how it works.
If you use findAll()
, I recommend you to use this:
$data_email = EmailArchive::model()->findAll(
array(
'condition' => 'email_id = :email_id',
'params' => array(':email_id' => $id)
)
);
For some reason only
df[, (names(df) %in% c("A","B","E"))]
worked for me. All of the above syntaxes yielded "undefined columns selected".
Another option is numpy.genfromtxt
, e.g:
import numpy as np
data = np.genfromtxt("myfile.dat",delimiter=",")
This will make data
a numpy array with as many rows and columns as are in your file
*EDIT: I wrote an article about how to do this https://medium.com/riow/mongodb-data-collection-change-85b63d96ff76
It's new in mongodb 3.6 https://docs.mongodb.com/manual/release-notes/3.6/ 2018/01/10
$ mongod --version
db version v3.6.2
In order to use changeStreams the database must be a Replication Set
More about Replication Sets: https://docs.mongodb.com/manual/replication/
Your Database will be a "Standalone" by default.
How to Convert a Standalone to a Replica Set: https://docs.mongodb.com/manual/tutorial/convert-standalone-to-replica-set/
The following example is a practical application for how you might use this.
* Specifically for Node.
/* file.js */
'use strict'
module.exports = function (
app,
io,
User // Collection Name
) {
// SET WATCH ON COLLECTION
const changeStream = User.watch();
// Socket Connection
io.on('connection', function (socket) {
console.log('Connection!');
// USERS - Change
changeStream.on('change', function(change) {
console.log('COLLECTION CHANGED');
User.find({}, (err, data) => {
if (err) throw err;
if (data) {
// RESEND ALL USERS
socket.emit('users', data);
}
});
});
});
};
/* END - file.js */
Useful links:
https://docs.mongodb.com/manual/tutorial/convert-standalone-to-replica-set
https://docs.mongodb.com/manual/tutorial/change-streams-example
https://docs.mongodb.com/v3.6/tutorial/change-streams-example
http://plusnconsulting.com/post/MongoDB-Change-Streams
This is very simple and easily manage.
jQuery(document).ready(function(){
jQuery("#search").click(function(){
jQuery("#loader").show("slow");
jQuery("#response_result").hide("slow");
jQuery.post(siteurl+"/ajax.php?q="passyourdata, function(response){
setTimeout("finishAjax('response_result', '"+escape(response)+"')", 850);
});
});
})
function finishAjax(id,response){
jQuery("#loader").hide("slow");
jQuery('#response_result').html(unescape(response));
jQuery("#"+id).show("slow");
return true;
}
I don't there there is any DataSource
for the gridview
Though you have DataBind
in your code as
gvdetails.DataBind();
Swift 5
I personally prefer the Timer with the block closure:
Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { (_) in
// TODO: - whatever you want
}
Just add a background image to all images using css:
img {
background: url('loading.gif') no-repeat;
}
bigint
)?Most of these answers fail on large integers (253 and larger): Bitwise tests(e.g. (x | 0) === x
), testing typeof x === 'number'
, regular int functions (e.g. parseInt
), regular arithmetics fail on large integers. This can be resolved by using BigInt
.
I've compiled several answers into one snippet to show the results. Most outright fail with large integers, while others work, except when passed the type BigInt
(e.g. 1n
). I've not included duplicate answers and have also left out any answers that allow decimals or don't attempt to test type)
// these all fail
n = 1000000000000000000000000000000
b = 1n
// These all fail on large integers
//https://stackoverflow.com/a/14636652/3600709
console.log('fail',1,n === parseInt(n, 10))
//https://stackoverflow.com/a/14794066/3600709
console.log('fail',2,!isNaN(n) && parseInt(Number(n)) == n && !isNaN(parseInt(n, 10)))
console.log('fail',2,!isNaN(n) && (parseFloat(n) | 0) === parseFloat(n))
console.log('fail',2,!isNaN(n) && (function(x) { return (x | 0) === x; })(parseFloat(n)))
//https://stackoverflow.com/a/21742529/3600709
console.log('fail',3,n == ~~n)
//https://stackoverflow.com/a/28211631/3600709
console.log('fail',4,!isNaN(n) && parseInt(n) == parseFloat(n))
//https://stackoverflow.com/a/41854178/3600709
console.log('fail',5,String(parseInt(n, 10)) === String(n))
// These ones work for integers, but not BigInt types (e.g. 1n)
//https://stackoverflow.com/a/14636725/3600709
console.log('partial',1,typeof n==='number' && (n%1)===0) // this one works
console.log('partial',1,typeof b==='number' && (b%1)===0) // this one fails
//https://stackoverflow.com/a/27424770/3600709
console.log('partial',2,Number.isInteger(n)) // this one works
console.log('partial',2,Number.isInteger(b)) // this one fails
//https://stackoverflow.com/a/14636638/3600709
console.log('partial',3,n % 1 === 0)
console.log('partial',3,b % 1 === 0) // gives uncaught type on BigInt
_x000D_
If you actually want to test the incoming value's type to ensure it's an integer, use this instead:
function isInt(value) {
try {
BigInt(value)
return !['string','object','boolean'].includes(typeof value)
} catch(e) {
return false
}
}
function isInt(value) {
try {
BigInt(value)
return !['string','object','boolean'].includes(typeof value)
} catch(e) {
return false
}
}
console.log('--- should be false')
console.log(isInt(undefined))
console.log(isInt(''))
console.log(isInt(null))
console.log(isInt({}))
console.log(isInt([]))
console.log(isInt(1.1e-1))
console.log(isInt(1.1))
console.log(isInt(true))
console.log(isInt(NaN))
console.log(isInt('1'))
console.log(isInt(function(){}))
console.log(isInt(Infinity))
console.log('--- should be true')
console.log(isInt(10))
console.log(isInt(0x11))
console.log(isInt(0))
console.log(isInt(-10000))
console.log(isInt(100000000000000000000000000000000000000))
console.log(isInt(1n))
_x000D_
If you don't care if the incoming type is actually boolean, string, etc. converted into a number, then just use the following:
function isInt(value) {
try {
BigInt(value)
return true
} catch(e) {
return false
}
}
function isInt(value) {
try {
BigInt(value)
return true
} catch(e) {
return false
}
}
console.log('--- should be false')
console.log(isInt(undefined))
console.log(isInt(null))
console.log(isInt({}))
console.log(isInt(1.1e-1))
console.log(isInt(1.1))
console.log(isInt(NaN))
console.log(isInt(function(){}))
console.log(isInt(Infinity))
console.log('--- should be true')
console.log(isInt(10))
console.log(isInt(0x11))
console.log(isInt(0))
console.log(isInt(-10000))
console.log(isInt(100000000000000000000000000000000000000))
console.log(isInt(1n))
// gets converted to number
console.log(isInt(''))
console.log(isInt([]))
console.log(isInt(true))
console.log(isInt('1'))
_x000D_
A silly hack I did was to set the height of the element to zero but overflow:visible; combining this with pointer-events:none; seems to cover all the bases.
.overlay {
height:0px;
overflow:visible;
pointer-events:none;
background:none !important;
}
Right from the docs:
-fpermissive
Downgrade some diagnostics about nonconformant code from errors to warnings. Thus, using-fpermissive
will allow some nonconforming code to compile.
Bottom line: don't use it unless you know what you are doing!
you can use
SELECT timestamp, value, card
FROM my_table
ORDER BY timestamp DESC
LIMIT 1
assuming you want also to sort by timestamp
?
JButton
has a model which answers these question:
isArmed()
, isPressed()
, isRollOVer()
etc. Hence you can ask the model for the answer you are seeking:
if(jButton1.getModel().isPressed())
System.out.println("the button is pressed");
In 2012 OData underwent standardization, so I'll just add an update here..
First the definitions:
REST - is an architecture of how to send messages over HTTP.
OData V4- is a specific implementation of REST, really defines the content of the messages in different formats (currently I think is AtomPub and JSON). ODataV4 follows rest principles.
For example, asp.net people will mostly use WebApi controller to serialize/deserialize objects into JSON and have javascript do something with it. The point of Odata is being able to query directly from the URL with out-of-the-box options.
The $.browser
method has been removed as of jQuery 1.9.
The
jQuery.browser()
method has been deprecated since jQuery 1.3 and is removed in 1.9. If needed, it is available as part of the jQuery Migrate plugin. We recommend using feature detection with a library such as Modernizr.
As stated in the Upgrade Guide you can try using the jQuery Migrate plugin to restore this functionality and let jQuery Tools work.
Based on the git documentation the best way is:
git remote -v
git remote set-url origin
where url-repository is the same URL that we get from the clone option.
I would strongly suggest using an npm package implementing correctly the base64 specification.
The best one I know is rfc4648
The problem is that btoa and atob use binary strings instead of Uint8Array and trying to convert to and from it is cumbersome. Also there is a lot of bad packages in npm for that. I lose a lot of time before finding that one.
The creators of that specific package did a simple thing: they took the specification of Base64 (which is here by the way) and implemented it correctly from the beginning to the end. (Including other formats in the specification that are also useful like Base64-url, Base32, etc ...) That doesn't seem a lot but apparently that was too much to ask to the bunch of other libraries.
So yeah, I know I'm doing a bit of proselytism but if you want to avoid losing your time too just use rfc4648.
Below code runs correctly.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double num1 = 3.12345678;
cout << fixed << showpoint;
cout << setprecision(2);
cout << num1 << endl;
}
I am providing the modern answer. The Timestamp
class is a hack on top of the already poorly designed java.util.Date
class and is long outdated. I am assuming, though, that you are getting a Timestamp
from a legacy API that you cannot afford to upgrade to java.time just now. When you do that, convert it to a modern Instant
and do further processing from there.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
.withLocale(Locale.GERMAN);
Timestamp oldfashionedTimestamp = new Timestamp(1_567_890_123_456L);
ZonedDateTime dateTime = oldfashionedTimestamp.toInstant()
.atZone(ZoneId.systemDefault());
String desiredFormat = dateTime.format(formatter);
System.out.println(desiredFormat);
Output in my time zone:
07.09.2019 23:02:03
Pick how long or short of a format you want by specifying FormatStyle.SHORT
, .MEDIUM
, .LONG
or .FULL
. Pick your own locale where I put Locale.GERMAN
. And pick your desired time zone, for example ZoneId.of("Europe/Oslo")
. A Timestamp
is a point in time without time zone, so we need a time zone to be able to convert it into year, month, day, hour, minute, etc. If your Timestamp
comes from a database value of type timestamp
without time zone (generally not recommended, but unfortunately often seen), ZoneId.systemDefault()
is likely to give you the correct result. Another and slightly simpler option in this case is instead to convert to a LocalDateTime
using oldfashionedTimestamp.toLocalDateTime()
and then format the LocalDateTime
in the same way as I did with the ZonedDateTime
.
Per @Beau's answer, Chrome does not support localhost CORS requests, and there is unlikely any change in this direction.
I use the Allow-Control-Allow-Origin: * Chrome Extension to go around this issue. The extension will add the necessary HTTP Headers for CORS:
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: "GET, PUT, POST, DELETE, HEAD, OPTIONS"
Access-Control-Expose-Headers: <you can add values here>
The source code is published on Github.
Note that the extension filter all URLs by default. This may break some websites (for example: Dropbox). I have changed it to filter only localhost URLs with the following URL filter
*://localhost:*/*
If you have data that has HTML tags and you want to display it so that a person can SEE the tags, use HttpServerUtility::HtmlEncode.
If you have data that has HTML tags in it and you want the user to see the tags rendered, then display the text as is. If the text represents an entire web page, use an IFRAME for it.
If you have data that has HTML tags and you want to strip out the tags and just display the unformatted text, use a regular expression.
Based on @ionden's answer, the call to the delegate could be simplified using null propagation since C# 6.0.
Your code would simply be:
class MyClass {
public event EventHandler MyEvent;
public void Method() {
MyEvent?.Invoke(this, EventArgs.Empty);
}
}
Use it like this:
MyClass myObject = new MyClass();
myObject.MyEvent += new EventHandler(myObject_MyEvent);
myObject.Method();
As an complement to Stefan Steiger answer: (as it doesn't look nice as a comment)
Extending String prototype:
String.prototype.b64encode = function() {
return btoa(unescape(encodeURIComponent(this)));
};
String.prototype.b64decode = function() {
return decodeURIComponent(escape(atob(this)));
};
Usage:
var str = "äöüÄÖÜçéèñ";
var encoded = str.b64encode();
console.log( encoded.b64decode() );
NOTE:
As stated in the comments, using unescape
is not recommended as it may be removed in the future:
Warning: Although unescape() is not strictly deprecated (as in "removed from the Web standards"), it is defined in Annex B of the ECMA-262 standard, whose introduction states: … All of the language features and behaviours specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification.
Note: Do not use unescape to decode URIs, use decodeURI or decodeURIComponent instead.
I think the only difference is the amount of syntactical sugar on each query. BETWEEN is just a slick way of saying exactly the same as the second query.
There might be some RDBMS specific difference that I'm not aware of, but I don't really think so.
you can use ES6 back quits
var inputs = [_x000D_
`<input type='checkbox' id='chbox0' onclick='checkboxChecked(this);'> <input type='text' class='noteinputs0'id='note` + 0 + `' placeholder='task0'><button id='notebtn0' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 1 + `' placeholder='task1'><button class='notebuttons' id='notebtn1' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 2 + `' placeholder='task2'><button class='notebuttons' id='notebtn2' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 3 + `' placeholder='task3'><button class='notebuttons' id='notebtn3' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 4 + `' placeholder='task4'><button class='notebuttons' id='notebtn4' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 5 + `' placeholder='task5'><button class='notebuttons' id='notebtn5' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 6 + `' placeholder='task6'><button class='notebuttons' id='notebtn6' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 7 + `' placeholder='task7'><button class='notebuttons' id='notebtn7' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 8 + `' placeholder='task8'><button class='notebuttons' id='notebtn8' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 9 + `' placeholder='task9'><button class='notebuttons' id='notebtn9' >creat</button>`_x000D_
].sort().join(" ");_x000D_
document.querySelector('#hi').innerHTML += `<br>` +inputs;
_x000D_
<div id="hi"></div>
_x000D_
String s = "1.210000";
while (s.endsWith("0")){
s = (s.substring(0, s.length() - 1));
}
This will make the string to drop the tailing 0-s.
need to delete show from class:
<div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion">
It have to be
<div id="collapseOne" class="collapse" aria-labelledby="headingOne" data-parent="#accordion">
// The interface
interface Blah {
void something();
}
...
// Something that expects an object implementing that interface
void chewOnIt(Blah b) {
b.something();
}
...
// Let's provide an object of an anonymous class
chewOnIt(
new Blah() {
@Override
void something() { System.out.println("Anonymous something!"); }
}
);
VS 2015 changes this. It added a .vs folder to my web project and the applicationhost.config was in there. I made the changes suggested (window authentication = true, anon=false) and it started delivering a username instead of a blank.
Stuffing things into the global and/or local namespaces is not a good idea. Using a dict is so some-other-language-ish ... d['constant-key'] = value
just looks awkward. Python is OO. In the words of a master: """Namespaces are one honking great idea -- let's do more of those!"""
Like this:
>>> class Record(object):
... pass
...
>>> r = Record()
>>> r.foo = 'oof'
>>> setattr(r, 'bar', 'rab')
>>> r.foo
'oof'
>>> r.bar
'rab'
>>> names = 'id description price'.split()
>>> values = [666, 'duct tape', 3.45]
>>> s = Record()
>>> for name, value in zip(names, values):
... setattr(s, name, value)
...
>>> s.__dict__ # If you are suffering from dict withdrawal symptoms
{'price': 3.45, 'id': 666, 'description': 'duct tape'}
>>>
Disclaimer This is by no means standard and there could very well be a better spring way of doing this. None of the above answers address the issues of wiring a public static field.
I wanted to accomplish three things.
My object looks like this
private static String BRANCH = "testBranch";
@Value("${content.client.branch}")
public void finalSetBranch(String branch) {
BRANCH = branch;
}
public static String BRANCH() {
return BRANCH;
}
We have checked off 1 & 2 already now how do we prevent calls to the setter, since we cannot hide it.
@Component
@Aspect
public class FinalAutowiredHelper {
@Before("finalMethods()")
public void beforeFinal(JoinPoint joinPoint) {
throw new FinalAutowiredHelper().new ModifySudoFinalError("");
}
@Pointcut("execution(* com.free.content.client..*.finalSetBranch(..))")
public void finalMethods() {}
public class ModifySudoFinalError extends Error {
private String msg;
public ModifySudoFinalError(String msg) {
this.msg = msg;
}
@Override
public String getMessage() {
return "Attempted modification of a final property: " + msg;
}
}
This aspect will wrap all methods beginning with final and throw an error if they are called.
I dont think this is particularly useful, but if you are ocd and like to keep you peas and carrots separated this is one way to do it safely.
Important Spring does not call your aspects when it calls a function. Made this easier, to bad I worked out the logic before figuring that out.
exec
is not an expression: a statement in Python 2.x, and a function in Python 3.x. It compiles and immediately evaluates a statement or set of statement contained in a string. Example:
exec('print(5)') # prints 5.
# exec 'print 5' if you use Python 2.x, nor the exec neither the print is a function there
exec('print(5)\nprint(6)') # prints 5{newline}6.
exec('if True: print(6)') # prints 6.
exec('5') # does nothing and returns nothing.
eval
is a built-in function (not a statement), which evaluates an expression and returns the value that expression produces. Example:
x = eval('5') # x <- 5
x = eval('%d + 6' % x) # x <- 11
x = eval('abs(%d)' % -100) # x <- 100
x = eval('x = 5') # INVALID; assignment is not an expression.
x = eval('if 1: x = 4') # INVALID; if is a statement, not an expression.
compile
is a lower level version of exec
and eval
. It does not execute or evaluate your statements or expressions, but returns a code object that can do it. The modes are as follows:
compile(string, '', 'eval')
returns the code object that would have been executed had you done eval(string)
. Note that you cannot use statements in this mode; only a (single) expression is valid.
compile(string, '', 'exec')
returns the code object that would have been executed had you done exec(string)
. You can use any number of statements here.
compile(string, '', 'single')
is like the exec
mode but expects exactly one expression/statement, eg compile('a=1 if 1 else 3', 'myf', mode='single')
I am using AWS sdk for uploads, after spending some time searching online i stumbled upon this thread. thanks to @lsimoneau 45581857 it turns out the exact same thing was happening. I simply pointed my request Url to the region on my bucket by attaching the region option and it worked.
const s3 = new AWS.S3({
accessKeyId: config.awsAccessKeyID,
secretAccessKey: config.awsSecretAccessKey,
region: 'eu-west-2' // add region here });
You can use the PHP printf
or sprintf
functions:
Example with sprintf
:
$num = 2.12;
echo sprintf("%.3f", $num);
You can run the same without echo
as well. Example: sprintf("%.3f", $num);
Output:
2.120
Alternatively, with printf
:
echo printf("%.2f", $num);
Output:
2.124
All these answers are partially wrong.
Microsoft has clarified that Community is for ANY USE as long as your revenue is under $1 Million US dollars. That is literally the only difference between Pro and Community. Corporate or free or not, irrelevant.
Even the lack of TFS support is not true. I can verify it is present and works perfectly.
EDIT: Here is an MSDN post regarding the $1M limit: MSDN (hint: it's in the VS 2017 license)
EDIT: Even over the revenue limit, open source is still free.
You could do something like this:
HTML
<div class="element">
<span>Hi, I am Murtaza</span>
</div>
jQuery
$(".element span").text(function(index, text) {
return text.replace('am', 'am not');
});
I think the better answer for this questions is
array_diff()
because it Compares array against one or more other arrays and returns the values in array that are not present in any of the other arrays.
Whereas
array_intersect() returns an array containing all the values of array that are present in all the arguments. Note that keys are preserved.
Have you looked at the Maven Dependency Plugin ? That won't remove stuff for you but has tools to allow you to do the analysis yourself. I'm thinking particularly of
mvn dependency:tree
//Declare the pointer and asign it to the function
bool (*pFunc)() = A;
//Call the function A
pFunc();
//Call function B
pFunc = B;
pFunc();
//Call function C
pFunc = C;
pFunc();
Try This in Code Behind and it will worked 100%
Write this line of code in you Code Behind file
string script = "window.onload = function() { YourJavaScriptFunctionName(); };";
ClientScript.RegisterStartupScript(this.GetType(), "YourJavaScriptFunctionName", script, true);
And this is the web form page
<script type="text/javascript">
function YourJavaScriptFunctionName() {
alert("Test!")
}
</script>
you need to use jboss-client.jar in your client project and you need to use jnp-client jar in your ejb project
Compound checking:
if (thing.foo && thing.foo.bar) {
... thing.foor.bar exists;
}
No, you can't make the img stretch to fit the div and simultaneously achieve the inverse. You would have an infinite resizing loop. However, you could take some notes from other answers and implement some min and max dimensions but that wasn't the question.
You need to decide if your image will scale to fit its parent or if you want the div to expand to fit its child img.
Using this block tells me you want the image size to be variable so the parent div is the width an image scales to. height: auto
is going to keep your image aspect ratio in tact. if you want to stretch the height it needs to be 100%
like this fiddle.
img {
width: 100%;
height: auto;
}
I guess you've meant:
[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
This would be sorted like this:
sorted(l,cmp=lambda x,y: cmp(x['name'],y['name']))
Replace:
Response.Write("<script language=javascript>alert('ERROR');</script>);
With
Response.Write("<script language=javascript>alert('ERROR');</script>");
In other words, you're missing a closing "
at the end of the Response.Write
statement.
It's worth mentioning that the code shown in the screenshot appears to correctly contain a closing double quote, however your best bet overall would be to use the ClientScriptManager.RegisterScriptBlock method:
var clientScript = Page.ClientScript;
clientScript.RegisterClientScriptBlock(this.GetType(), "AlertScript", "alert('ERROR')'", true);
This will take care of wrapping the script with <script>
tags and writing the script into the page for you.
Select the platform to be iPhone Simulator then click Build and Go. If it builds correctly then it will launch the simulator and run. If it does not build ok then it will indicate errors at the bottom of the window on the right hand side.
If you only have the app file then you would need to manually install that into the simulator. The simulator was not designed to be used this way, but I'm sure it would be possible, even if it was incredibly difficult.
If you have the source code (.proj .m .h etc) files then it should be a simple case of build and go.
Without dragging ostream into it:
constexpr char const* to_c_str(bool b) {
return
std::array<char const*, 2>{"false", "true "}[b]
;
};
You can create something like c using CSS multiple-backgrounds.
div {
background: linear-gradient(red, red),
linear-gradient(blue, blue),
linear-gradient(green, green);
background-size: 30% 50%,
30% 60%,
40% 80%;
background-position: 0% top,
calc(30% * 100 / (100 - 30)) top,
calc(60% * 100 / (100 - 40)) top;
background-repeat: no-repeat;
}
Note, you still have to use linear-gradients for background types, because CSS will not allow you to control the background-size of a single color layer. So here we just make a single-color gradient. Then you can control the size/position of each of those blocks of color independently. You also have to make sure they don't repeat, or they'll just expand and cover the whole image.
The trickiest part here is background-position. A background-position of 0% puts your element's left edge at the left. 100% puts its right edge at the right. 50% centers is middle.
For a fun bit of math to solve that, you can guess the transform is probably linear, and just solve two little slope-intercept equations.
// (at 0%, the div's left edge is 0% from the left)
0 = m * 0 + b
// (at 100%, the div's right edge is 100% - width% from the left)
100 = m * (100 - width) + b
b = 0, m = 100 / (100 - width)
so to position our 40% wide div 60% from the left, we put it at 60% * 100 / (100 - 40) (or use css-calc).
I got the same error in ibmcloud. I added namespace and then tried to push my image, it resolved the issue.
ibmcloud cr namespace-add txts
There are some working solutions here already, but here's another one:
>>> import types
>>> class Dummy: pass
>>> type(Dummy) is types.ClassType
True
Perhaps useful online checker PEP8 : http://pep8online.com/
Use ./catalina.sh start
to start Tomcat. Do ./catalina.sh
to get the usage.
I am using apache-tomcat-6.0.36.
I'm not sure if this would be a common mistake, but if you do something like:
$var = 'value' .= 'value2';
this will also produce the same error
Can't use method return value in write context
You can't have an =
and a .=
in the same statement. You can use one or the other, but not both.
Note, I understand this is unrelated to the actual code in the question, however this question is the top result when searching for the error message, so I wanted to post it here for completeness.
From the docs:
Note: When actions are enclosed in tasks (such as FutureTask) either explicitly or via methods such as submit, these task objects catch and maintain computational exceptions, and so they do not cause abrupt termination, and the internal exceptions are not passed to this method.
When you submit a Runnable, it'll get wrapped in a Future.
Your afterExecute should be something like this:
public final class ExtendedExecutor extends ThreadPoolExecutor {
// ...
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
if (t == null && r instanceof Future<?>) {
try {
Future<?> future = (Future<?>) r;
if (future.isDone()) {
future.get();
}
} catch (CancellationException ce) {
t = ce;
} catch (ExecutionException ee) {
t = ee.getCause();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
if (t != null) {
System.out.println(t);
}
}
}
Sounds like ehcache is overkill for what you want, however note that it does not need external configuration files.
It is generally a good idea to move configuration into a declarative configuration files ( so you don't need to recompile when a new installation requires a different expiry time ), but it is not at all required, you can still configure it programmatically. http://www.ehcache.org/documentation/user-guide/configuration
Add new column to your table and perfrom the query:
UPDATE tbl SET combined = CONCAT(zipcode, ' - ', city, ', ', state)
After try to solve this problem in my workspace I found a solution.
This error is because there are a problem with Metro using some combinations of NPM and Node version.
You have 2 alternatives:
Alternative 2: Go to this file: \node_modules\metro-config\src\defaults\blacklist.js
and change this code:
var sharedBlacklist = [
/node_modules[/\\]react[/\\]dist[/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];
and change to this:
var sharedBlacklist = [
/node_modules[\/\\]react[\/\\]dist[\/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];
Please note that if you run an
npm install
or ayarn install
you need to change the code again.
It may be something like this in HTML:
<div class="container-outer">
<div class="container-inner">
<!-- Your images over here -->
</div>
</div>
With this stylesheet:
.container-outer { overflow: scroll; width: 500px; height: 210px; }
.container-inner { width: 10000px; }
You can even create an intelligent script to calculate the inner container width, like this one:
$(document).ready(function() {
var container_width = SINGLE_IMAGE_WIDTH * $(".container-inner a").length;
$(".container-inner").css("width", container_width);
});
$(JSON.parse(response)).map(function () {
return $('<option>').val(this.value).text(this.label);
}).appendTo('#selectorId');
Spring source code to explain how ApplicationContextAware work
when you use ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
In AbstractApplicationContext
class,the refresh()
method have the following code:
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
enter this method,beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
will add ApplicationContextAwareProcessor to AbstractrBeanFactory.
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
beanFactory.setBeanClassLoader(getClassLoader());
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
...........
When spring initialize bean in AbstractAutowireCapableBeanFactory
,
in method initializeBean
,call applyBeanPostProcessorsBeforeInitialization
to implement the bean post process. the process include inject the applicationContext.
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessBeforeInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
when BeanPostProcessor implement Objectto execute the postProcessBeforeInitialization method,for example ApplicationContextAwareProcessor
that added before.
private void invokeAwareInterfaces(Object bean) {
if (bean instanceof Aware) {
if (bean instanceof EnvironmentAware) {
((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
}
if (bean instanceof EmbeddedValueResolverAware) {
((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(
new EmbeddedValueResolver(this.applicationContext.getBeanFactory()));
}
if (bean instanceof ResourceLoaderAware) {
((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
}
if (bean instanceof ApplicationEventPublisherAware) {
((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
}
if (bean instanceof MessageSourceAware) {
((MessageSourceAware) bean).setMessageSource(this.applicationContext);
}
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
}
}
}
if symfony version less than 2.8
sudo chmod -R 777 app/cache/*
_x000D_
if symfony version great than or equal 3.0
sudo chmod -R 777 var/cache/*
_x000D_
A char simply contains a single alphabet and a string has a full word or number of words woth having a escape sequence inserted in the end automatically to tell the compiler that string has been ended here.(0)
For this particular case it's better to do a = None
instead of del a
. This will decrement reference count to object a
was (if any) assigned to and won't fail when a
is not defined. Note, that del
statement doesn't call destructor of an object directly, but unbind it from variable. Destructor of object is called when reference count became zero.
For setting up virtualenv on a clean Ubuntu installation, I found this zookeeper tutorial to be the best - you can ignore the parts about zookeper itself. The virtualenvwrapper documentation offers similar content, but it's a bit scarce on telling you what exactly to put into your .bashrc
file.
<script id="add-active-to-current-page-nav-link" type="text/javascript">
function setSelectedPageNav() {
var pathName = document.location.pathname;
if ($("nav ul li a") != null) {
var currentLink = $("nav ul li a[href='" + pathName + "']");
currentLink.addClass("active");
}
}
setSelectedPageNav();
</script>
Below is what I do to copy a database from production env to my local env:
The SimpleDateFormat class has a method called SetTimeZone(TimeZone) that is inherited from the DateFormat class. http://docs.oracle.com/javase/6/docs/api/java/text/DateFormat.html
Addition to @BalusC 's answer. You also need to set width of headers. In my case, below css can only apply to my table's column width.
.myTable td:nth-child(1),.myTable th:nth-child(1) {
width: 20px;
}
Similar to yebmouxing I could not the
xhr.getResponseHeader('Set-Cookie');
method to work. It would only return null even if I had set HTTPOnly to false on my server.
I too wrote a simple js helper function to grab the cookies from the document. This function is very basic and only works if you know the additional info (lifespan, domain, path, etc. etc.) to add yourself:
function getCookie(cookieName){
var cookieArray = document.cookie.split(';');
for(var i=0; i<cookieArray.length; i++){
var cookie = cookieArray[i];
while (cookie.charAt(0)==' '){
cookie = cookie.substring(1);
}
cookieHalves = cookie.split('=');
if(cookieHalves[0]== cookieName){
return cookieHalves[1];
}
}
return "";
}
There is the JavaScriptSerializer class you can use too. That will let you deserialize the json to a .NET object. There's a generic Deserialize<T>
, though you will need the .NET object to have a similar signature as the javascript one. Additionally there is also a DeserializeObject
method that just makes a plain object
. You can then use reflection to get at the properties you need.
If your controller takes a FormCollection
, and you didn't add anything else to the data
the json should be in form[0]
:
public ActionResult Save(FormCollection forms) {
string json = forms[0];
// do your thing here.
}
If you really need to override css that has !important rules in it, for instance, in a case I ran into recently, overriding a wordpress theme required !important scss rules to break the theme, but since I was transpiling my code with webpack and (I assume this is why --)my css came along in the chain after the transpiled javascript, you can add a separate class rule in your stylesheet that overrides the first !important rule in the cascade, and toggle the heavier-weighted class rather than adjusting css dynamically. Just a thought.
The best explanation can be found here: Python @Property Explained – How to Use and When? (Full Examples) by Selva Prabhakaran | Posted on November 5, 2018
It helped me understand WHY not only HOW.
I had a similar issue. Using chrome://net-internals/#events I was able to see that my issue was due to some silent redirect. My get request was being fired in an onload script. The url was of the form, "http://example.com/inner-path" and the 301 was permanently redirecting to "/inner-path". To fix the issue I just changed the url to "/inner-path" and that fixed the issue. I still don't know why a script that worked a week ago was suddenly giving me issue... Hope this helps someone
For .NET Core 2.2 you can publish the application and set the target to be a self-contained executable.
In Visual Studio right click your console application project. Select publish to folder and set the profile settings like so:
You'll find your compiled code with the .exe in the publish folder.
It allows for you to give the jQuery variable a different name, and still use it:
<script type="text/javascript">
$jq = $.noConflict();
// Code that uses other library's $ can follow here.
//use $jq for all calls to jQuery:
$jq.ajax(...)
$jq('selector')
</script>
In Laravel 5
public function index(Request $request) {
$request->ip();
}
$date = "Mar 03, 2011";
$date = strtotime($date);
$date = strtotime("+7 day", $date);
echo date('M d, Y', $date);
Render Line Endings is a VS Code extension that is still actively maintained (as of Apr 2020):
https://marketplace.visualstudio.com/items?itemName=medo64.render-crlf
https://github.com/medo64/render-crlf/
It can be configured like this:
{
"editor.renderWhitespace": "all",
"code-eol.newlineCharacter": "¬",
"code-eol.returnCharacter" : "¤",
"code-eol.crlfCharacter" : "¤¬",
}
and looks like this:
In Swift5 ans Xcode 10
Add two textfields with Save and Cancel actions and read TextFields text data
func alertWithTF() {
//Step : 1
let alert = UIAlertController(title: "Great Title", message: "Please input something", preferredStyle: UIAlertController.Style.alert )
//Step : 2
let save = UIAlertAction(title: "Save", style: .default) { (alertAction) in
let textField = alert.textFields![0] as UITextField
let textField2 = alert.textFields![1] as UITextField
if textField.text != "" {
//Read TextFields text data
print(textField.text!)
print("TF 1 : \(textField.text!)")
} else {
print("TF 1 is Empty...")
}
if textField2.text != "" {
print(textField2.text!)
print("TF 2 : \(textField2.text!)")
} else {
print("TF 2 is Empty...")
}
}
//Step : 3
//For first TF
alert.addTextField { (textField) in
textField.placeholder = "Enter your first name"
textField.textColor = .red
}
//For second TF
alert.addTextField { (textField) in
textField.placeholder = "Enter your last name"
textField.textColor = .blue
}
//Step : 4
alert.addAction(save)
//Cancel action
let cancel = UIAlertAction(title: "Cancel", style: .default) { (alertAction) in }
alert.addAction(cancel)
//OR single line action
//alert.addAction(UIAlertAction(title: "Cancel", style: .default) { (alertAction) in })
self.present(alert, animated:true, completion: nil)
}
For more explanation https://medium.com/@chan.henryk/alert-controller-with-text-field-in-swift-3-bda7ac06026c
Installing specific laravel version with composer create-project
composer global require laravel/installer
Then, if you want install specific version then just edit version values "6." , "5.8."
composer create-project --prefer-dist laravel/laravel Projectname "6.*"
Run Local Development Server
php artisan serve
function call asStartOfDay()
on java.time.LocalDate
object returns a java.time.LocalDateTime
object
Try bower install git://github.com/urin/jquery.balloon.js.git#1.0.3 --save
where 1.0.3
is the tag number which you can get by reading tag under releases. Also for URL replace by git://
in order for system to connect.
ResponseEntity
is meant to represent the entire HTTP response. You can control anything that goes into it: status code, headers, and body.
@ResponseBody
is a marker for the HTTP response body and @ResponseStatus
declares the status code of the HTTP response.
@ResponseStatus
isn't very flexible. It marks the entire method so you have to be sure that your handler method will always behave the same way. And you still can't set the headers. You'd need the HttpServletResponse
or a HttpHeaders
parameter.
Basically, ResponseEntity
lets you do more.
If I'm starting a long-running process like a copy or hash and I want to know later how long it took, I just do this:
$ date; sha1sum reallybigfile.txt; date
Which will result in the following output:
Tue Jun 2 21:16:03 PDT 2015
5089a8e475cc41b2672982f690e5221469390bc0 reallybigfile.txt
Tue Jun 2 21:33:54 PDT 2015
Granted, as implemented here it isn't very precise and doesn't calculate the elapsed time. But it's dirt simple and sometimes all you need.
Use the str
accessor with square brackets:
df['col'] = df['col'].str[:9]
Or str.slice:
df['col'] = df['col'].str.slice(0, 9)
for(int i=0;i<ytFiles.size();i++){
int key = ytFiles.keyAt(i);
Log.e("key", String.valueOf(key));
String format = ytFiles.get(key).getFormat().toString();
String url = ytFiles.get(key).getUrl();
Log.e("url",url);
}
you can get key by method keyat and you have to pass the index then it will return key at that particular index. this loop will get all the key
Maybe I am off the mark here and not understanding the OP but why are you joining tables?
If you have a table with members and this table has a column named "group_id", you can just run a query on the members table to get a count of the members grouped by the group_id.
SELECT group_id, COUNT(*) as membercount
FROM members
GROUP BY group_id
HAVING membercount > 4
This should have the least overhead simply because you are avoiding a join but should still give you what you wanted.
If you want the group details and description etc, then add a join from the members table back to the groups table to retrieve the name would give you the quickest result.
Yeah. Queue
LinkedList being the most trivial concrete implementation.
I was getting the same error, even after following Google's guide at https://developers.google.com/drive/api/v3/quickstart/python, then I realized I had to invoke like this:
python3 quickstart.py
Instead of:
python quickstart.py <-- WRONG
(Note the "3
")
Worked flawlessly.
I'm using Ubuntu 18.04.4 LTS
.
A quick easy approach if you are not concerned about query params:
header("location: ./");
You can also capitalize the first letter of the match using \I1
and \I2
etc instead of $1
and $2
.
you can use this:
box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2);
as seen on: https://stackoverflow.com/a/24084708/8953378
You might have seen my answer to another C question where I mentioned FSM! Here is how I do it:
FSM {
STATE(x) {
...
NEXTSTATE(y);
}
STATE(y) {
...
if (x == 0)
NEXTSTATE(y);
else
NEXTSTATE(x);
}
}
With the following macros defined
#define FSM
#define STATE(x) s_##x :
#define NEXTSTATE(x) goto s_##x
This can be modified to suit the specific case. For example, you may have a file FSMFILE
that you want to drive your FSM, so you could incorporate the action of reading next char into the the macro itself:
#define FSM
#define STATE(x) s_##x : FSMCHR = fgetc(FSMFILE); sn_##x :
#define NEXTSTATE(x) goto s_##x
#define NEXTSTATE_NR(x) goto sn_##x
now you have two types of transitions: one goes to a state and read a new character, the other goes to a state without consuming any input.
You can also automate the handling of EOF with something like:
#define STATE(x) s_##x : if ((FSMCHR = fgetc(FSMFILE) == EOF)\
goto sx_endfsm;\
sn_##x :
#define ENDFSM sx_endfsm:
The good thing of this approach is that you can directly translate a state diagram you draw into working code and, conversely, you can easily draw a state diagram from the code.
In other techniques for implementing FSM the structure of the transitions is buried in control structures (while, if, switch ...) and controlled by variables value (tipically a state
variable) and it may be a complex task to relate the nice diagram to a convoluted code.
I learned this technique from an article appeared on the great "Computer Language" magazine that, unfortunately, is no longer published.
B business day frequency
C custom business day frequency (experimental)
D calendar day frequency
W weekly frequency
M month end frequency
SM semi-month end frequency (15th and end of month)
BM business month end frequency
CBM custom business month end frequency
MS month start frequency
SMS semi-month start frequency (1st and 15th)
BMS business month start frequency
CBMS custom business month start frequency
Q quarter end frequency
BQ business quarter endfrequency
QS quarter start frequency
BQS business quarter start frequency
A year end frequency
BA, BY business year end frequency
AS, YS year start frequency
BAS, BYS business year start frequency
BH business hour frequency
H hourly frequency
T, min minutely frequency
S secondly frequency
L, ms milliseconds
U, us microseconds
N nanoseconds
See the timeseries documentation. It includes a list of offsets (and 'anchored' offsets), and a section about resampling.
Note that there isn't a list of all the different how
options, because it can be any NumPy array function and any function that is available via groupby dispatching can be passed to how
by name.
You have to loop through every cell in the range "D3:D6"
and construct your To
string. Simply assigning it to a variant will not solve the purpose. EmailTo
becomes an array if you assign the range directly to it. You can do this as well but then you will have to loop through the array to create your To
string
Is this what you are trying? (TRIED AND TESTED)
Option Explicit
Sub Mail_workbook_Outlook_1()
'Working in 2000-2010
'This example send the last saved version of the Activeworkbook
Dim OutApp As Object
Dim OutMail As Object
Dim emailRng As Range, cl As Range
Dim sTo As String
Set emailRng = Worksheets("Selections").Range("D3:D6")
For Each cl In emailRng
sTo = sTo & ";" & cl.Value
Next
sTo = Mid(sTo, 2)
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = sTo
.CC = "[email protected];[email protected]"
.BCC = ""
.Subject = "RMA #" & Worksheets("RMA").Range("E1")
.Body = "Attached to this email is RMA #" & _
Worksheets("RMA").Range("E1") & _
". Please follow the instructions for your department included in this form."
.Attachments.Add ActiveWorkbook.FullName
'You can add other files also like this
'.Attachments.Add ("C:\test.txt")
.Display
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
You just need to add 'table-layout: fixed;'
.table {
display: table;
height: 100px;
width: 100%;
table-layout: fixed;
}
To avoid problems of character encoding in sending emails using the class PHPMailer we can configure it to send it with UTF-8 character encoding using the "CharSet" parameter, as we can see in the following Php code:
$mail = new PHPMailer();
$mail->From = '[email protected]';
$mail->FromName = 'Mi nombre';
$mail->AddAddress('[email protected]');
$mail->Subject = 'Prueba';
$mail->Body = '';
$mail->IsHTML(true);
// Active condition utf-8
$mail->CharSet = 'UTF-8';
// Send mail
$mail->Send();
Converting a varchar
value into an int
fails when the value includes a decimal point to prevent loss of data.
If you convert to a decimal
or float
value first, then convert to int
, the conversion works.
Either example below will return 7082:
SELECT CONVERT(int, CONVERT(decimal(12,7), '7082.7758172'));
SELECT CAST(CAST('7082.7758172' as float) as int);
Be aware that converting to a float
value may result, in rare circumstances, in a loss of precision. I would tend towards using a decimal
value, however you'll need to specify precision and scale values that make sense for the varchar
data you're converting.
Instead of 1:nrow(mydata_2)
you can simply use the which()
function: which(mydata_2[,4] == 1578)
Although as it was pointed out above, the 3rd column contains 1578, not the fourth:
which(mydata_2[,3] == 1578)
In case you want store the value:
Pair.of<List<>, List<>> output = opt.map(details -> Pair.of(details.a, details.b))).orElseGet(() -> Pair.of(Collections.emptyList(), Collections.emptyList()));
It's hard to know how to help you without understanding the context / structure of your data, but I believe this might help you:
SELECT
SUM(CASE WHEN column1 IS NOT NULL THEN 1 ELSE 0 END) AS column1_count
,SUM(CASE WHEN column2 IS NOT NULL THEN 1 ELSE 0 END) AS column2_count
,SUM(CASE WHEN column3 IS NOT NULL THEN 1 ELSE 0 END) AS column3_count
FROM table
I know this is an old post and I do favor extension methods, but here's a simple class I use from time to time to handle dictionaries when I need default values.
I wish this were just part of the base Dictionary class.
public class DictionaryWithDefault<TKey, TValue> : Dictionary<TKey, TValue>
{
TValue _default;
public TValue DefaultValue {
get { return _default; }
set { _default = value; }
}
public DictionaryWithDefault() : base() { }
public DictionaryWithDefault(TValue defaultValue) : base() {
_default = defaultValue;
}
public new TValue this[TKey key]
{
get {
TValue t;
return base.TryGetValue(key, out t) ? t : _default;
}
set { base[key] = value; }
}
}
Beware, however. By subclassing and using new
(since override
is not available on the native Dictionary
type), if a DictionaryWithDefault
object is upcast to a plain Dictionary
, calling the indexer will use the base Dictionary
implementation (throwing an exception if missing) rather than the subclass's implementation.
Ordinarily, float
s aren't counted in the layout of their parents.
To prevent that, add overflow: hidden
to the parent.
Use this method
public static void setColumnWidths(JTable table, int... widths) {
TableColumnModel columnModel = table.getColumnModel();
for (int i = 0; i < widths.length; i++) {
if (i < columnModel.getColumnCount()) {
columnModel.getColumn(i).setMaxWidth(widths[i]);
}
else break;
}
}
Or extend the JTable
class:
public class Table extends JTable {
public void setColumnWidths(int... widths) {
for (int i = 0; i < widths.length; i++) {
if (i < columnModel.getColumnCount()) {
columnModel.getColumn(i).setMaxWidth(widths[i]);
}
else break;
}
}
}
And then
table.setColumnWidths(30, 150, 100, 100);
You can open SQL Compact 4.0 Databases from Visual Studio 2012 directly, by going to
and following the instructions there.
If you're okay with them being upgraded to 4.0, you can open older versions of SQL Compact Databases also - handy if you just want to have a look at some tables, etc for stuff like Windows Phone local database development.
(note I'm not sure if this requires a specific SKU of VS2012, if it helps I'm running Premium)
You can use various options with FINDSTR to remove the lines do not want, like so:
DIR /S | FINDSTR "\-" | FINDSTR /VI DIR
Normal output contains entries like these:
28-Aug-14 05:14 PM <DIR> .
28-Aug-14 05:14 PM <DIR> ..
You could remove these using the various filtering options offered by FINDSTR. You can also use the excellent unxutils, but it converts the output to UNIX by default, so you no longer get CR+LF; FINDSTR offers the best Windows option.
Just try this line:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
after:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
In my case, my parent pom had a parent:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>some version</version>
<relativePath/>
</parent>
After changing to importing a spring pom:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>some version</version>
<type>pom</type>
<scope>import</scope>
</dependency>
My unit tests started to run
restart: on-failure
did the trick for me..see below
---
version: '2.1'
services:
consumer:
image: golang:alpine
volumes:
- ./:/go/src/srv-consumer
working_dir: /go/src/srv-consumer
environment:
AMQP_DSN: "amqp://guest:guest@rabbitmq:5672"
command: go run cmd/main.go
links:
- rabbitmq
restart: on-failure
rabbitmq:
image: rabbitmq:3.7-management-alpine
ports:
- "15672:15672"
- "5672:5672"
Using Python's built in range function:
Python 2
input = 8
output = range(input + 1)
print output
[0, 1, 2, 3, 4, 5, 6, 7, 8]
Python 3
input = 8
output = list(range(input + 1))
print(output)
[0, 1, 2, 3, 4, 5, 6, 7, 8]
I don't think using JS for creating a button is good practice. What if the user's browser deactivates JavaScript ?
Plus, you can just use a checkbox and a bit of CSS to do it. And it easy to retrieve the state of your checkbox.
This is just one example, but you can style it how want.
HTML
<fieldset class="toggle">
<input id="data-policy" type="checkbox" checked="checked" />
<label for="data-policy">
<div class="toggle-button">
<div class="toggle-tab"></div>
</div>
Toggle
</label>
</fieldset>?
CSS
.toggle label {
color: #444;
float: left;
line-height: 26px;
}
.toggle .toggle-button {
margin: 0px 10px 0px 0px;
float: left;
width: 70px;
height: 26px;
background-color: #eeeeee;
background-image: -webkit-gradient(linear, left top, left bottom, from(#eeeeee), to(#fafafa));
background-image: -webkit-linear-gradient(top, #eeeeee, #fafafa);
background-image: -moz-linear-gradient(top, #eeeeee, #fafafa);
background-image: -o-linear-gradient(top, #eeeeee, #fafafa);
background-image: -ms-linear-gradient(top, #eeeeee, #fafafa);
background-image: linear-gradient(top, #eeeeee, #fafafa);
filter: progid:dximagetransform.microsoft.gradient(GradientType=0, StartColorStr='#eeeeee', EndColorStr='#fafafa');
border-radius: 4px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border: 1px solid #D1D1D1;
}
.toggle .toggle-button .toggle-tab {
width: 30px;
height: 26px;
background-color: #fafafa;
background-image: -webkit-gradient(linear, left top, left bottom, from(#fafafa), to(#eeeeee));
background-image: -webkit-linear-gradient(top, #fafafa, #eeeeee);
background-image: -moz-linear-gradient(top, #fafafa, #eeeeee);
background-image: -o-linear-gradient(top, #fafafa, #eeeeee);
background-image: -ms-linear-gradient(top, #fafafa, #eeeeee);
background-image: linear-gradient(top, #fafafa, #eeeeee);
filter: progid:dximagetransform.microsoft.gradient(GradientType=0, StartColorStr='#fafafa', EndColorStr='#eeeeee');
border: 1px solid #CCC;
margin-left: -1px;
margin-top: -1px;
border-radius: 4px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
-webkit-box-shadow: 5px 0px 4px -5px #000000, 0px 0px 0px 0px #000000;
-moz-box-shadow: 5px 0px 4px -5px rgba(0, 0, 0, 0.3), 0px 0px 0px 0px #000000;
box-shadow: 5px 0px 4px -5px rgba(0, 0, 0, 0.3), 0px 0px 0px 0px #000000;
}
.toggle input[type=checkbox] {
display: none;
}
.toggle input[type=checkbox]:checked ~ label .toggle-button {
background-color: #2d71c2;
background-image: -webkit-gradient(linear, left top, left bottom, from(#2d71c2), to(#4ea1db));
background-image: -webkit-linear-gradient(top, #2d71c2, #4ea1db);
background-image: -moz-linear-gradient(top, #2d71c2, #4ea1db);
background-image: -o-linear-gradient(top, #2d71c2, #4ea1db);
background-image: -ms-linear-gradient(top, #2d71c2, #4ea1db);
background-image: linear-gradient(top, #2d71c2, #4ea1db);
filter: progid:dximagetransform.microsoft.gradient(GradientType=0, StartColorStr='#2d71c2', EndColorStr='#4ea1db');
}
.toggle input[type=checkbox]:checked ~ label .toggle-button .toggle-tab {
margin-left: 39px;
-webkit-box-shadow: -5px 0px 4px -5px #000000, 0px 0px 0px 0px #000000;
-moz-box-shadow: -5px 0px 4px -5px rgba(0, 0, 0, 0.3), 0px 0px 0px 0px #000000;
box-shadow: -5px 0px 4px -5px rgba(0, 0, 0, 0.3), 0px 0px 0px 0px #000000;
}?
Hope this helps
I write a file dir.php
var files = <?php $out = array();
foreach (glob('file/*.html') as $filename) {
$p = pathinfo($filename);
$out[] = $p['filename'];
}
echo json_encode($out); ?>;
In your script add:
<script src='dir.php'></script>
and use the files[] array
How to get rid of a header(first row) and an index(first column).
To write to CSV file:
df = pandas.DataFrame(your_array)
df.to_csv('your_array.csv', header=False, index=False)
To read from CSV file:
df = pandas.read_csv('your_array.csv')
a = df.values
If you want to read a CSV file that doesn't contain a header, pass additional parameter header
:
df = pandas.read_csv('your_array.csv', header=None)
Though you already have an accepted answer, I figured I'd add this for anyone else interested in a different solution-
An implementation could be as follows:
import csv
with open('C:/mypath/to/csvfile.csv', 'r') as f:
d_reader = csv.DictReader(f)
#get fieldnames from DictReader object and store in list
headers = d_reader.fieldnames
for line in d_reader:
#print value in MyCol1 for each row
print(line['MyCol1'])
In the above, d_reader.fieldnames returns a list of your headers (assuming the headers are in the top row). Which allows...
>>> print(headers)
['MyCol1', 'MyCol2', 'MyCol3']
If your headers are in, say the 2nd row (with the very top row being row 1), you could do as follows:
import csv
with open('C:/mypath/to/csvfile.csv', 'r') as f:
#you can eat the first line before creating DictReader.
#if no "fieldnames" param is passed into
#DictReader object upon creation, DictReader
#will read the upper-most line as the headers
f.readline()
d_reader = csv.DictReader(f)
headers = d_reader.fieldnames
for line in d_reader:
#print value in MyCol1 for each row
print(line['MyCol1'])
Talking about efficiency:
document.getElementById( 'elemtId' ).style.display = 'none';
What jQuery does with its .show()
and .hide()
methods is, that it remembers the last state of an element. That can come in handy sometimes, but since you asked about efficiency that doesn't matter here.
public void interrupt()
Interrupts this thread.
Unless the current thread is interrupting itself, which is always permitted, the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.
If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.
If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.
If none of the previous conditions hold then this thread's interrupt status will be set.
Interrupting a thread that is not alive need not have any effect.
Throws: SecurityException - if the current thread cannot modify this thread
Found this "plug-and-play" function here. Worked like a charm!
import subprocess
def myrun(cmd):
"""from http://blog.kagesenshi.org/2008/02/teeing-python-subprocesspopen-output.html
"""
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout = []
while True:
line = p.stdout.readline()
stdout.append(line)
print line,
if line == '' and p.poll() != None:
break
return ''.join(stdout)
I do one of two things in this scenario
Implement a serialize/deserialize system for my objects and pass them as Strings (in JSON format usually, but you can serialize them any way you'd like)
Implement a container that lives outside of the activities so that all my activities can read and write to this container. You can make this container static or use some kind of dependency injection to retrieve the same instance in each activity.
Parcelable works just fine, but I always found it to be an ugly looking pattern and doesn't really add any value that isn't there if you write your own serialization code outside of the model.
Simple Way to add JTextArea in JScrollBar with JScrollPan
import javax.swing.*;
public class ScrollingTextArea
{
JFrame f;
JTextArea ta;
JScrollPane scrolltxt;
public ScrollingTextArea()
{
// TODO Auto-generated constructor stub
f=new JFrame();
f.setLayout(null);
f.setVisible(true);
f.setSize(500,500);
ta=new JTextArea();
ta.setBounds(5,5,100,200);
scrolltxt=new JScrollPane(ta);
scrolltxt.setBounds(3,3,400,400);
f.add(scrolltxt);
}
public static void main(String[] args)
{
new ScrollingTextArea();
}
}
In addition to answer of @jww, I would like to say that the configuration in openssl-ca.cnf,
default_days = 1000 # How long to certify for
defines the default number of days the certificate signed by this root-ca will be valid. To set the validity of root-ca itself you should use '-days n' option in:
openssl req -x509 -days 3000 -config openssl-ca.cnf -newkey rsa:4096 -sha256 -nodes -out cacert.pem -outform PEM
Failing to do so, your root-ca will be valid for only the default one month and any certificate signed by this root CA will also have validity of one month.
You need to decide the length of the zip code (which I believe should be 5 characters long). Then you need to tell MySQL to zero-fill the numbers.
Let's suppose your table is called mytable
and the field in question is zipcode
, type smallint
. You need to issue the following query:
ALTER TABLE mytable CHANGE `zipcode` `zipcode`
MEDIUMINT( 5 ) UNSIGNED ZEROFILL NOT NULL;
The advantage of this method is that it leaves your data intact, there's no need to use triggers during data insertion / updates, there's no need to use functions when you SELECT
the data and that you can always remove the extra zeros or increase the field length should you change your mind.
Generally, the parameters are what are used inside the function and the arguments are the values passed when the function is called. (Unless you take the opposite view — Wikipedia mentions alternative conventions when discussing parameters and arguments).
double sqrt(double x)
{
...
return x;
}
void other(void)
{
double two = sqrt(2.0);
}
Under my thesis, x is the parameter to sqrt()
and 2.0 is the argument.
The terms are often used at least somewhat interchangeably.
The RegExp constructor creates a regular expression object for matching text with a pattern.
var pattern1 = ':\\(|:=\\(|:-\\(';
var pattern2 = ':\\(|:=\\(|:-\\(|:\\(|:=\\(|:-\\(';
var regex = new RegExp(pattern1 + '|' + pattern2, 'gi');
str.match(regex);
Above code works perfectly for me...
grep LMN20113456 LMN2011*
or if you want to search recursively through subdirectories:
find . -type f -name 'LMN2011*' -exec grep LMN20113456 {} \;
It's simple-
SELECT empname,
empid,
(SELECT COUNT (profileid)
FROM profile
WHERE profile.empid = employee.empid)
AS number_of_profiles
FROM employee;
It is even simpler when you use a table join like this:
SELECT e.empname, e.empid, COUNT (p.profileid) AS number_of_profiles
FROM employee e LEFT JOIN profile p ON e.empid = p.empid
GROUP BY e.empname, e.empid;
Explanation for the subquery:
Essentially, a subquery in a select
gets a scalar value and passes it to the main query. A subquery in select
is not allowed to pass more than one row and more than one column, which is a restriction. Here, we are passing a count
to the main query, which, as we know, would always be only a number- a scalar value. If a value is not found, the subquery returns null
to the main query. Moreover, a subquery can access columns from the from
clause of the main query, as shown in my query where employee.empid
is passed from the outer query to the inner query.
Edit:
When you use a subquery in a select
clause, Oracle essentially treats it as a left join (you can see this in the explain plan for your query), with the cardinality of the rows being just one on the right for every row in the left.
Explanation for the left join
A left join is very handy, especially when you want to replace the select
subquery due to its restrictions. There are no restrictions here on the number of rows of the tables in either side of the LEFT JOIN
keyword.
For more information read Oracle Docs on subqueries and left join or left outer join.
there are multiple ways to do this without using any third-party code or libraries (the recommended way).
1st STATIC WAY: create a .json file then import it in your react component example
my file name is "example.json"
{"example" : "my text"}
the example key inside the example.json can be anything just keep in mind to use double quotes to prevent future issues.
How to import in react component
import myJson from "jsonlocation";
and you can use it anywhere like this
myJson.example
now there are a few things to consider. With this method, you are forced to declare your import at the top of the page and cannot dynamically import anything.
Now, what about if we want to dynamically import the JSON data? example a multi-language support website?
2 DYNAMIC WAY
1st declare your JSON file exactly like my example above
but this time we are importing the data differently.
let language = require('./en.json');
this can access the same way.
but wait where is the dynamic load?
here is how to load the JSON dynamically
let language = require(`./${variable}.json`);
now make sure all your JSON files are within the same directory
here you can use the JSON the same way as the first example
myJson.example
what changed? the way we import because it is the only thing we really need.
I hope this helps.
you may be create function before so, update your function again using.
Alter FUNCTION dbo.Afisho_rankimin(@emri_rest int)
RETURNS int
AS
BEGIN
Declare @rankimi int
Select @rankimi=dbo.RESTORANTET.Rankimi
From RESTORANTET
Where dbo.RESTORANTET.ID_Rest=@emri_rest
RETURN @rankimi
END
GO
SELECT dbo.Afisho_rankimin(5) AS Rankimi
GO
Check this:
String.format(str,STR[])
For instance:
String.format( "Put your %s where your %s is", "money", "mouth" );
From RFC 6750, Section 1.2:
Bearer Token
A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).
The Bearer Token or Refresh token is created for you by the Authentication server. When a user authenticates your application (client) the authentication server then goes and generates for your a Bearer Token (refresh token) which you can then use to get an access token.
The Bearer Token is normally some kind of cryptic value created by the authentication server, it isn't random it is created based upon the user giving you access and the client your application getting access.
See also: Mozilla MDN Header Information.
How about BOM, the magical character Microsoft adds to start of files (at least XML)?
I know this has already been answered, but for anybody looking for a simple, no-frills implementation of a ViewPager indicator, I've implemented one that I've open sourced. For anyone finding Jake Wharton's version a bit complex for their needs, have a look at https://github.com/jarrodrobins/SimpleViewPagerIndicator.
i had the same problem . i just convert
@Styles.Render("~/Content/css")
and @Scripts.Render("~/bundles/modernizr") to
@Styles.Render("/Content/css")
@Scripts.Render("/bundles/modernizr")
and its worked. just dont forget to convert
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
to
@Scripts.Render("/bundles/jquery")
@Scripts.Render("/bundles/bootstrap")
have nice time
A little test that shows how to parse a date in ISO8601 and that LocalDateTime does not handle DSTs.
@Test
public void shouldHandleDaylightSavingTimes() throws ParseException {
//ISO8601 UTC date format
SimpleDateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
// 1 hour of difference between 2 dates in UTC happening at the Daylight Saving Time
Date d1 = utcFormat.parse("2019-10-27T00:30:00.000Z");
Date d2 = utcFormat.parse("2019-10-27T01:30:00.000Z");
//Date 2 is before date 2
Assert.assertTrue(d1.getTime() < d2.getTime());
// And there is 1 hour difference between the 2 dates
Assert.assertEquals(1000*60*60, d2.getTime() - d1.getTime());
//Print the dates in local time
SimpleDateFormat localFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm z Z", Locale.forLanguageTag("fr_CH"));
localFormat.setTimeZone(TimeZone.getTimeZone("Europe/Zurich"));
//Both dates are at 02h30 local time (because of DST), but one is CEST +0200 and the other CET +0100 (clock goes backwards)
Assert.assertEquals("2019-10-27 02:30 CEST +0200", localFormat.format(d1));
Assert.assertEquals("2019-10-27 02:30 CET +0100", localFormat.format(d2));
//Small test that shows that LocalDateTime does not handle DST (and should not be used for storing timeseries data)
LocalDateTime ld1 = LocalDateTime.ofInstant(d1.toInstant(), ZoneId.of("Europe/Zurich"));
LocalDateTime ld2 = LocalDateTime.ofInstant(d2.toInstant(), ZoneId.of("Europe/Zurich"));
//Note that a localdatetime does not handle DST, therefore the 2 dates are the same
Assert.assertEquals(ld1, ld2);
//They both have the following local values
Assert.assertEquals(2019, ld1.getYear());
Assert.assertEquals(27, ld1.getDayOfMonth());
Assert.assertEquals(10, ld1.getMonthValue());
Assert.assertEquals(2, ld1.getHour());
Assert.assertEquals(30, ld1.getMinute());
Assert.assertEquals(0, ld1.getSecond());
}
OP's solution to his problem, as he says, has dubious output. That code still shows confusion about representations of time. To clear up this confusion, and make code that won't lead to wrong times, consider this extension of what he did:
public static void _testDateFormatting() {
SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat sdfGMT2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
sdfGMT2.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat sdfLocal1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
SimpleDateFormat sdfLocal2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
try {
Date d = new Date();
String s1 = d.toString();
String s2 = sdfLocal1.format(d);
// Store s3 or s4 in database.
String s3 = sdfGMT1.format(d);
String s4 = sdfGMT2.format(d);
// Retrieve s3 or s4 from database, using LOCAL sdf.
String s5 = sdfLocal1.parse(s3).toString();
//EXCEPTION String s6 = sdfLocal2.parse(s3).toString();
String s7 = sdfLocal1.parse(s4).toString();
String s8 = sdfLocal2.parse(s4).toString();
// Retrieve s3 from database, using GMT sdf.
// Note that this is the SAME sdf that created s3.
Date d2 = sdfGMT1.parse(s3);
String s9 = d2.toString();
String s10 = sdfGMT1.format(d2);
String s11 = sdfLocal2.format(d2);
} catch (Exception e) {
e.printStackTrace();
}
}
examining values in a debugger:
s1 "Mon Sep 07 06:11:53 EDT 2015" (id=831698113128)
s2 "2015.09.07 06:11:53" (id=831698114048)
s3 "2015.09.07 10:11:53" (id=831698114968)
s4 "2015.09.07 10:11:53 GMT+00:00" (id=831698116112)
s5 "Mon Sep 07 10:11:53 EDT 2015" (id=831698116944)
s6 -- omitted, gave parse exception
s7 "Mon Sep 07 10:11:53 EDT 2015" (id=831698118680)
s8 "Mon Sep 07 06:11:53 EDT 2015" (id=831698119584)
s9 "Mon Sep 07 06:11:53 EDT 2015" (id=831698120392)
s10 "2015.09.07 10:11:53" (id=831698121312)
s11 "2015.09.07 06:11:53 EDT" (id=831698122256)
sdf2 and sdfLocal2 include time zone, so we can see what is really going on. s1 & s2 are at 06:11:53 in zone EDT. s3 & s4 are at 10:11:53 in zone GMT -- equivalent to the original EDT time. Imagine we save s3 or s4 in a data base, where we are using GMT for consistency, so we can have times from anywhere in the world, without storing different time zones.
s5 parses the GMT time, but treats it as a local time. So it says "10:11:53" -- the GMT time -- but thinks it is 10:11:53 in local time. Not good.
s7 parses the GMT time, but ignores the GMT in the string, so still treats it as a local time.
s8 works, because now we include GMT in the string, and the local zone parser uses it to convert from one time zone to another.
Now suppose you don't want to store the zone, you want to be able to parse s3, but display it as a local time. The answer is to parse using the same time zone it was stored in -- so use the same sdf as it was created in, sdfGMT1. s9, s10, & s11 are all representations of the original time. They are all "correct". That is, d2 == d1. Then it is only a question of how you want to DISPLAY it. If you want to display what is stored in DB -- GMT time -- then you need to format it using a GMT sdf. Ths is s10.
So here is the final solution, if you don't want to explicitly store with " GMT" in the string, and want to display in GMT format:
public static void _testDateFormatting() {
SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
Date d = new Date();
String s3 = sdfGMT1.format(d);
// Store s3 in DB.
// ...
// Retrieve s3 from database, using GMT sdf.
Date d2 = sdfGMT1.parse(s3);
String s10 = sdfGMT1.format(d2);
} catch (Exception e) {
e.printStackTrace();
}
}
You can use LinkedHashMap to main insertion order in Map
The important points about Java LinkedHashMap class are:
A LinkedHashMap contains values based on the key 3.It may have one null key and multiple null values. 4.It is same as HashMap instead maintains insertion order
public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>
But if you want sort values in map using User-defined object or any primitive data type key then you should use TreeMap For more information, refer this link
$('input[type="text"]').get().some(item => item.value !== '');
it is different for different icons.(eg, diff sizes for action bar icons, laucnher icons, etc.) please follow this link icons handbook to learn more.
Disclaimer: I have been exposed to a significant amount of F77
The modern equivalent of goto
(arguable, only my opinion, etc) is explicit exception handling:
Edited to highlight the code reuse better.
Pretend pseudocode in a fake python-like language with goto
:
def myfunc1(x)
if x == 0:
goto LABEL1
return 1/x
def myfunc2(z)
if z == 0:
goto LABEL1
return 1/z
myfunc1(0)
myfunc2(0)
:LABEL1
print 'Cannot divide by zero'.
Compared to python:
def myfunc1(x):
return 1/x
def myfunc2(y):
return 1/y
try:
myfunc1(0)
myfunc2(0)
except ZeroDivisionError:
print 'Cannot divide by zero'
Explicit named exceptions are a significantly better way to deal with non-linear conditional branching.
Step 1:
select object_name, s.sid, s.serial#, p.spid
from v$locked_object l, dba_objects o, v$session s, v$process p
where l.object_id = o.object_id and l.session_id = s.sid and s.paddr = p.addr;
Step 2:
alter system kill session 'sid,serial#'; --`sid` and `serial#` get from step 1
More info: http://www.oracle-base.com/articles/misc/killing-oracle-sessions.php
If your html link is like this:
<a class ="linkClass" href="https://stackoverflow.com/"> Stack Overflow</a>
Then you can access the href in jquery as given below (there is no need to use "a" in href for this)
$(".linkClass").on("click",accesshref);
function accesshref()
{
var url = $(".linkClass").attr("href");
//OR
var url = $(this).attr("href");
}
Apache Commons Math package has a factorial method, I think you could use that.
Image Magick has been mentioned. There is a JNI front end project called JMagick. It's not a particularly stable project (and Image Magick itself has been known to change a lot and even break compatibility). That said, we've had good experience using JMagick and a compatible version of Image Magick in a production environment to perform scaling at a high throughput, low latency rate. Speed was substantially better then with an all Java graphics library that we previously tried.
I know it has been answered good few times already, but I like below way of doing this. I hope it will help someone.
//attach object (search for row)
TableName tn = _context.TableNames.Attach(new TableName { PK_COLUMN = YOUR_VALUE});
// set new value
tn.COLUMN_NAME_TO_UPDATE = NEW_COLUMN_VALUE;
// set column as modified
_context.Entry<TableName>(tn).Property(tnp => tnp.COLUMN_NAME_TO_UPDATE).IsModified = true;
// save change
_context.SaveChanges();
If you just want to remove "username1" you can use a simple replace.
name.replace("username1,", "")
or you could use split like you mentioned.
var name = "username1, username2 and username3 like this post.".split(",")[1];
$("h1").text(name);
jsfiddle example
You need to add dynamically created components to entryComponents
inside your @NgModule
@NgModule({
declarations: [
AppComponent,
LoginComponent,
DashboardComponent,
HomeComponent,
DialogResultExampleDialog
],
entryComponents: [DialogResultExampleDialog]
Note: In some cases entryComponents
under lazy loaded modules will not work, as a workaround put them in your app.module
(root)
This is not actually adding the CSS to the cell, but gives the same effect. While providing the same result as others above, this version is a little more intuitive to me, but I'm a novice, so take it for what it's worth:
$(".hoverCell").bind('mouseover', function() {
var old_color = $(this).css("background-color");
$(this)[0].style.backgroundColor = '#ffff00';
$(".hoverCell").bind('mouseout', function () {
$(this)[0].style.backgroundColor = old_color;
});
});
This requires setting the Class for each of the cells you want to highlight to "hoverCell".
Try Foo.instance_methods.include? :bar
In computer programming, particularly in the C, C++, and C# programming languages, a variable or object declared with the volatile
keyword usually has special properties related to optimization and/or threading. Generally speaking, the volatile
keyword is intended to prevent the (pseudo)compiler from applying any optimizations on the code that assume values of variables cannot change "on their own." (c) Wikipedia
To add to rcs' answer, if you want to use position_dodge() with geom_bar() when x is a POSIX.ct date, you must multiply the width by 86400, e.g.,
ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) +
geom_bar(position = "dodge", stat = 'identity') +
geom_text(aes(label=Number), position=position_dodge(width=0.9*86400), vjust=-0.25)
Please refer below Ajax overview:
Return string from function
#include <stdio.h>
const char* greet() {
return "Hello";
}
int main(void) {
printf("%s", greet());
}
Make sure this is included in your Info.plist:
<key>CFBundlePackageType</key>
<string>APPL</string>
I had APPL misspelled as AAPL. Once I fixed that and signed into Application Loader and Xcode with the same Apple ID, everything worked.
I had the problem, I had to replace "Not Available" with NA
and my solution goes like this
data <- sapply(data,function(x) {x <- gsub("Not Available",NA,x)})
"I understand both are server cluster management software."
This statement isn't entirely true. Kubernetes doesn't manage server clusters, it orchestrates containers such that they work together with minimal hassle and exposure. Kubernetes allows you to define parts of your application as "pods" (one or more containers) that are delivered by "deployments" or "daemon sets" (and a few others) and exposed to the outside world via services. However, Kubernetes doesn't manage the cluster itself (there are tools that can provision, configure and scale clusters for you, but those are not part of Kubernetes itself).
Mesos on the other hand comes closer to "cluster management" in that it can control what's running where, but not just in terms of scheduling containers. Mesos also manages standalone software running on the cluster servers. Even though it's mostly used as an alternative to Kubernetes, Mesos can easily work with Kubernetes as while the functionality overlaps in many areas, Mesos can do more (but on the overlapping parts Kubernetes tends to be better).
In my instance, I was running an abnormal query to fix data. If you lock the tables in your query, then you won't have to deal with the Lock timeout:
LOCK TABLES `customer` WRITE;
update customer set account_import_id = 1;
UNLOCK TABLES;
This is probably not a good idea for normal use.
For more info see: MySQL 8.0 Reference Manual
Use MySQL Workbench. create SQL dump file of your database
Follow below steps:
Maybe you can try this: though please note - This pulls the column count, not the row count
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
int count = reader.VisibleFieldCount;
Console.WriteLine(count);
}
}
I wrote this function it does just the right thing. Interpolate a word starting with $
with the value of the variable of the same name.
private static String interpol1(String x){
Field[] ffield = Main.class.getDeclaredFields();
String[] test = x.split(" ") ;
for (String v : test ) {
for ( Field n: ffield ) {
if(v.startsWith("$") && ( n.getName().equals(v.substring(1)) )){
try {
x = x.replace("$" + v.substring(1), String.valueOf( n.get(null)));
}catch (Exception e){
System.out.println("");
}
}
}
}
return x;
}
As simple as that
private static byte[] getByteArrayFromByteBuffer(ByteBuffer byteBuffer) {
byte[] bytesArray = new byte[byteBuffer.remaining()];
byteBuffer.get(bytesArray, 0, bytesArray.length);
return bytesArray;
}
None of the above things worked for me as I had multiple recipients both in 'to' and 'cc'. So I tried like below:
recipients = ['[email protected]', '[email protected]']
cc_recipients = ['[email protected]', '[email protected]']
MESSAGE['To'] = ", ".join(recipients)
MESSAGE['Cc'] = ", ".join(cc_recipients)
and extend the 'recipients' with 'cc_recipients' and send mail in trivial way
recipients.extend(cc_recipients)
server.sendmail(FROM,recipients,MESSAGE.as_string())
To connect use ssh like so:
ssh -i keyname.pem [email protected]
Where keyname.pem
is the name of your private key, username
is the correct username for your os distribution, and xxx.xx.xxx.xx
is the public ip address.
When it times out or fails, check the following:
Make sure to have an inbound rule for tcp port 22 and either all ips or your ip. You can find the security group through the ec2 menu, in the instance options.
For a new subnet in a vpc, you need to change to a routing table that points 0.0.0.0/0 to internet gateway target. When you create the subnet in your vpc, by default it assigns the default routing table, which probably does not accept incoming traffic from the internet. You can edit the routing table options in the vpc menu and then subnets.
For an instance in a vpc, you need to assign a public elastic ip address, and associate it with the instance. The private ip address can't be accessed from the outside. You can get an elastic ip in the ec2 menu (not instance menu).
Make sure you're using the correct username. It should be one of ec2-user
or root
or ubuntu
. Try them all if necessary.
Make sure you're using the correct private key (the one you download or choose when launching the instance). Seems obvious, but copy paste got me twice.
I resolved by adding - %AppData%\npm\node_modules@angular\cli\bin\ path to my environment variables path
Simple:
dim input as string = "SPQR"
dim format as string =""
dim result as string = ""
'pad left:
format = "{0,-8}"
result = String.Format(format,input)
'result = "SPQR "
'pad right
format = "{0,8}"
result = String.Format(format,input)
'result = " SPQR"
Try writing the following batch file and executing it:
Echo one
cmd
Echo two
cmd
Echo three
cmd
Only the first two lines get executed. But if you type "exit" at the command prompt, the next two lines are processed. It's a shell loading another.
To be sure that this is not what is happening in your script, just type "exit" when the first command ends.
HTH!
New method for an old question
It seems like in the answers provided the issue was always how the box border would either be visible on the left and right of the object or you'd have to inset it so far that it didn't shadow the whole length of the container properly.
This example uses the :after
pseudo element along with a linear gradient with transparency in order to put a drop shadow on a container that extends exactly to the sides of the element you wish to shadow.
Worth noting with this solution is that if you use padding on the element that you wish to drop shadow, it won't display correctly. This is because the after
pseudo element appends it's content directly after the elements inner content. So if you have padding, the shadow will appear inside the box. This can be overcome by eliminating padding on outer container (where the shadow applies) and using an inner container where you apply needed padding.
Example with padding and background color on the shadowed div:
If you want to change the depth of the shadow, simply increase the height
style in the after
pseudo element. You can also obviously darken, lighten, or change colors in the linear gradient styles.
body {_x000D_
background: #eee;_x000D_
}_x000D_
_x000D_
.bottom-shadow {_x000D_
width: 80%;_x000D_
margin: 0 auto;_x000D_
}_x000D_
_x000D_
.bottom-shadow:after {_x000D_
content: "";_x000D_
display: block;_x000D_
height: 8px;_x000D_
background: transparent;_x000D_
background: -moz-linear-gradient(top, rgba(0,0,0,0.4) 0%, rgba(0,0,0,0) 100%); /* FF3.6-15 */_x000D_
background: -webkit-linear-gradient(top, rgba(0,0,0,0.4) 0%,rgba(0,0,0,0) 100%); /* Chrome10-25,Safari5.1-6 */_x000D_
background: linear-gradient(to bottom, rgba(0,0,0,0.4) 0%,rgba(0,0,0,0) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */_x000D_
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#a6000000', endColorstr='#00000000',GradientType=0 ); /* IE6-9 */_x000D_
}_x000D_
_x000D_
.bottom-shadow div {_x000D_
padding: 18px;_x000D_
background: #fff;_x000D_
}
_x000D_
<div class="bottom-shadow">_x000D_
<div>_x000D_
Shadows, FTW!_x000D_
</div>_x000D_
</div>
_x000D_
Most of the time this happens due to the invalid response type from server.
Make sure the following 2 to avoid this issue..
Based on Rubens' solution, you need to enable Delayed Expansion of env variables (type "help setlocal" or "help cmd") so that the var is correctly evaluated in the loop:
@echo off
setlocal enabledelayedexpansion
set myvar=the list:
for /r %%i In (*.sql) DO set myvar=!myvar! %%i,
echo %myvar%
Also consider the following restriction (MSDN):
The maximum individual environment variable size is 8192bytes.
I managed to get FTP access to the customer's server and so was able to track down the problem.
After the form is POSTed, I authenticate the user and then redirect to the main part of the app.
Util::redirect('/apps/content');
The error was occurring not on the posting of the form, but on the redirect immediately following it. For some reason, IIS was continuing to presume the POST method for the redirect, and then objecting to the POST to /apps/content
as it's a directory.
The error message never indicated that it was the following page that was generating the error - thanks Microsoft!
The solution was to add a trailing slash:
Util::redirect('/apps/content/');
IIS could then resolve the redirect to a default document as is no longer attempting to POST to a directory.
import java.util.*;
public class HexadeciamlToBinary
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("enter the hexadecimal number");
String s=sc.nextLine();
String p="";
long n=0;
int c=0;
for(int i=s.length()-1;i>=0;i--)
{
if(s.charAt(i)=='A')
{
n=n+(long)(Math.pow(16,c)*10);
c++;
}
else if(s.charAt(i)=='B')
{
n=n+(long)(Math.pow(16,c)*11);
c++;
}
else if(s.charAt(i)=='C')
{
n=n+(long)(Math.pow(16,c)*12);
c++;
}
else if(s.charAt(i)=='D')
{
n=n+(long)(Math.pow(16,c)*13);
c++;
}
else if(s.charAt(i)=='E')
{
n=n+(long)(Math.pow(16,c)*14);
c++;
}
else if(s.charAt(i)=='F')
{
n=n+(long)(Math.pow(16,c)*15);
c++;
}
else
{
n=n+(long)Math.pow(16,c)*(long)s.charAt(i);
c++;
}
}
String s1="",k="";
if(n>1)
{
while(n>0)
{
if(n%2==0)
{
k=k+"0";
n=n/2;
}
else
{
k=k+"1";
n=n/2;
}
}
for(int i=0;i<k.length();i++)
{
s1=k.charAt(i)+s1;
}
System.out.println("The respective binary number is : "+s1);
}
else
{
System.out.println("The respective binary number is : "+n);
}
}
}
To have deselect (DidDeselectRowAt) fire when clicked the first time because of preloaded data; you need inform the tableView that the row is already selected to begin with, so that an initial click then deselects the row:
//Swift 3:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView[indexPath.row] == "data value"
tableView.selectRow(at: indexPath, animated: false, scrollPosition: UITableViewScrollPosition.none)
}
}
In the POSIX standard clock
has its return value defined in terms of the CLOCKS_PER_SEC symbol and an implementation is free to define this in any convenient fashion. Under Linux, I have had good luck with the times()
function.
Standard CSS3 rotate should work in IE9, but I believe you need to give it a vendor prefix, like so:
-ms-transform: rotate(10deg);
It is possible that it may not work in the beta version; if not, try downloading the current preview version (preview 7), which is a later revision that the beta. I don't have the beta version to test against, so I can't confirm whether it was in that version or not. The final release version is definitely slated to support it.
I can also confirm that the IE-specific filter
property has been dropped in IE9.
[Edit]
People have asked for some further documentation. As they say, this is quite limited, but I did find this page: http://css3please.com/ which is useful for testing various CSS3 features in all browsers.
But testing the rotate feature on this page in IE9 preview caused it to crash fairly spectacularly.
However I have done some independant tests using -ms-transform:rotate()
in IE9 in my own test pages, and it is working fine. So my conclusion is that the feature is implemented, but has got some bugs, possibly related to setting it dynamically.
Another useful reference point for which features are implemented in which browsers is www.canIuse.com -- see http://caniuse.com/#search=rotation
[EDIT]
Reviving this old answer because I recently found out about a hack called CSS Sandpaper which is relevant to the question and may make things easier.
The hack implements support for the standard CSS transform
for for old versions of IE. So now you can add the following to your CSS:
-sand-transform: rotate(10deg);
...and have it work in IE 6/7/8, without having to use the filter
syntax. (of course it still uses the filter syntax behind the scenes, but this makes it a lot easier to manage because it's using similar syntax to other browsers)
if mysql is okay for you:
SELECT flights.*,
fromairports.city as fromCity,
toairports.city as toCity
FROM flights
LEFT JOIN (airports as fromairports, airports as toairports)
ON (fromairports.code=flights.fairport AND toairports.code=flights.tairport )
WHERE flights.fairport = '?' OR fromairports.city = '?'
edit: added example to filter the output for code or city
As you mention, you need to specify the right namespace. You also see this error with an incorrect namespace.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip">
will not work.
Change:
xmlns="http://schemas.android.com/apk/res/android"
to
xmlns:android="http://schemas.android.com/apk/res/android"
The error message is referring to everything that starts "android:" as the XML does not know what the "
android:
" namespace is.
xmlns:android
defines it.
npm ls
npm list
is just an alias for npm ls
For the extended info use
npm la
npm ll
You can always set --depth=0
at the end to get the first level deep.
npm ls --depth=0
You can check development and production packages.
npm ls --only=dev
npm ls --only=prod
To show the info in json
format
npm ls --json=true
The default is false
npm ls --json=false
You can insist on long format to show extended information.
npm ls --long=true
You can show parseable output instead of tree view.
npm ls --parseable=true
You can list packages in the global install prefix instead of in the current project.
npm ls --global=true
npm ls -g // shorthand
Full documentation you can find here.
If you don't need full debugging support, you can now view JavaScript console logs directly within Chrome for iOS at chrome://inspect.
https://blog.chromium.org/2019/03/debugging-websites-in-chrome-for-ios.html
DeZign for Databases should be able to do this just fine.
You can do it using FullscreenVideoView
class. Its a small library project. It's video progress dialog is build in. it's gradle is :
compile 'com.github.rtoshiro.fullscreenvideoview:fullscreenvideoview:1.1.0'
your VideoView xml is like this
<com.github.rtoshiro.view.video.FullscreenVideoLayout
android:id="@+id/videoview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
In your activity , initialize it using this way:
FullscreenVideoLayout videoLayout;
videoLayout = (FullscreenVideoLayout) findViewById(R.id.videoview);
videoLayout.setActivity(this);
Uri videoUri = Uri.parse("YOUR_VIDEO_URL");
try {
videoLayout.setVideoURI(videoUri);
} catch (IOException e) {
e.printStackTrace();
}
That's it. Happy coding :)
If want to know more then visit here
Edit: gradle path has been updated. compile it now
compile 'com.github.rtoshiro.fullscreenvideoview:fullscreenvideoview:1.1.2'
NuPKG files are just zip files, so anything that can process a zip file should be able to process a nupkg file, i.e, 7zip.
if you're using jQuery you would have:
$('#elementId').change(function() { alert('Do Stuff'); });
or MS AJAX:
$addHandler($get('elementId'), 'change', function(){ alert('Do Stuff'); });
Or in the raw HTML of the element:
<input type="text" onchange="alert('Do Stuff');" id="myElement" />
After re-reading the question I think I miss-read what was to be done. I've never found a way to update a DOM element in a manner which will force a change event, what you're best doing is having a separate event handler method, like this:
$addHandler($get('elementId'), 'change', elementChanged);
function elementChanged(){
alert('Do Stuff!');
}
function editElement(){
var el = $get('elementId');
el.value = 'something new';
elementChanged();
}
Since you're already writing a JavaScript method which will do the changing it's only 1 additional line to call.
Or, if you are using the Microsoft AJAX framework you can access all the event handlers via:
$get('elementId')._events
It'd allow you to do some reflection-style workings to find the right event handler(s) to fire.