Use Assembly.GetTypes
. For example:
Assembly mscorlib = typeof(string).Assembly;
foreach (Type type in mscorlib.GetTypes())
{
Console.WriteLine(type.FullName);
}
We declare a variable 'a'
SET **@a** = (SELECT MAX( customer_id ) FROM customers) +1;
INSERT INTO customers
( customer_id, firstname, surname )
VALUES
(**@a**, 'jim', 'sock')
If I m calling the method by using SubClass name MysubClass then subclass method display what it means static method can be overridden or not
class MyClass {
static void myStaticMethod() {
System.out.println("Im in sta1");
}
}
class MySubClass extends MyClass {
static void myStaticMethod() {
System.out.println("Im in sta123");
}
}
public class My {
public static void main(String arg[]) {
MyClass myObject = new MyClass();
myObject.myStaticMethod();
// should be written as
MyClass.myStaticMethod();
// calling from subclass name
MySubClass.myStaticMethod();
myObject = new MySubClass();
myObject.myStaticMethod();
// still calls the static method in MyClass, NOT in MySubClass
}
}
Make sure if your table doesn't already have rows whose Primary Key values are same as the the Primary Key Id in your Query.
I opened this thread looking for a quick solution to a simple question, but I found that the answers here were either not helpful or overly complicated. The best way to get the last 5 chars of a string is, in fact, to use the Right() method. Here is a simple example:
Dim sMyString, sLast5 As String
sMyString = "I will be going to school in 2011!"
sLast5 = Right(sMyString, - 5)
MsgBox("sLast5 = " & sLast5)
If you're getting an error then there is probably something wrong with your syntax. Also, with the Right() method you don't need to worry much about going over or under the string length. In my example you could type in 10000 instead of 5 and it would just MsgBox the whole string, or if sMyString was NULL or "", the message box would just pop up with nothing.
It may be as simple as installing git on the remote host (like it was in my case).
sudo apt-get install git
Or equivalent for other package management systems.
What worked for me is to install XCode 6.1 (compatible with iOS 8.1)
If you want to select particular element use below code
var gridRowData = $("<your grid name>").data("kendoGrid");
var selectedItem = gridRowData.dataItem(gridRowData.select());
var quote = selectedItem["<column name>"];
Follow this one
$teacher_id = '';
for ($i = 0; $i < count($data['teacher_id']); $i++) {
$teacher_id .= $data['teacher_id'][$i].',';
}
$teacher_id = rtrim($teacher_id, ',');
echo $teacher_id; exit;
URLEncoder
is the way to go. You only need to keep in mind to encode only the individual query string parameter name and/or value, not the entire URL, for sure not the query string parameter separator character &
nor the parameter name-value separator character =
.
String q = "random word £500 bank $";
String url = "https://example.com?q=" + URLEncoder.encode(q, StandardCharsets.UTF_8);
When you're still not on Java 10 or newer, then use StandardCharsets.UTF_8.toString()
as charset argument, or when you're still not on Java 7 or newer, then use "UTF-8"
.
Note that spaces in query parameters are represented by +
, not %20
, which is legitimately valid. The %20
is usually to be used to represent spaces in URI itself (the part before the URI-query string separator character ?
), not in query string (the part after ?
).
Also note that there are three encode()
methods. One without Charset
as second argument and another with String
as second argument which throws a checked exception. The one without Charset
argument is deprecated. Never use it and always specify the Charset
argument. The javadoc even explicitly recommends to use the UTF-8 encoding, as mandated by RFC3986 and W3C.
All other characters are unsafe and are first converted into one or more bytes using some encoding scheme. Then each byte is represented by the 3-character string "%xy", where xy is the two-digit hexadecimal representation of the byte. The recommended encoding scheme to use is UTF-8. However, for compatibility reasons, if an encoding is not specified, then the default encoding of the platform is used.
Suspend the process with CTRL+Z then use the command bg
to resume it in background. For example:
sleep 60
^Z #Suspend character shown after hitting CTRL+Z
[1]+ Stopped sleep 60 #Message showing stopped process info
bg #Resume current job (last job stopped)
More about job control and bg
usage in bash
manual page:
JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.
EDIT
To start a process where you can even kill the terminal and it still carries on running
nohup [command] [-args] > [filename] 2>&1 &
e.g.
nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &
To just ignore the output (not very wise) change the filename to /dev/null
To get the error message set to a different file change the &1
to a filename.
In addition: You can use the jobs
command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1
or kill %2
with the number being the index of the process.
If you are using C++, why don't you use std::string
instead of C-style strings?
std::string one="Hello";
std::string two="World";
std::string three= one+two;
If you need to pass this string to a C-function, simply pass three.c_str()
There are numerous Flexbox bugs in IE11 and other browsers - see flexbox on Can I Use -> Known Issues, where the following are listed under IE11:
display: flex
and flex-direction: column
will not properly calculate their flexed childrens' sizes if the container has min-height
but no explicit height
propertymin-height
is usedAlso see Philip Walton's Flexbugs list of issues and workarounds.
Try:
select v.*, row_number() over (partition by id order by elem) rn from
(select
id,
unnest(string_to_array(elements, ',')) AS elem
from myTable) v
I found the accepted solution didn't work on my MySQL install, returning an empty set, but this query worked for me in all situations that I tested it on:
SELECT x.val from data x, data y
GROUP BY x.val
HAVING SUM(SIGN(1-SIGN(y.val-x.val)))/COUNT(*) > .5
LIMIT 1
One option you could consider is using CSS variables. The idea is that you set the property you want to change to a CSS variable. Then, within your JS, change that variable's value.
See example below
function changeColor(newColor) {
document.documentElement.style.setProperty("--anchor-hover-color", newColor);
// ^^^^^^^^^^^-- select the root
}
_x000D_
:root {
--anchor-hover-color: red;
}
a:hover {
color: var(--anchor-hover-color);
}
_x000D_
<a href="#">Hover over me</a>
<button onclick="changeColor('lime')">Change to lime</button>
<button onclick="changeColor('red')">Change to red</button>
_x000D_
We can resolve this warning by adding this code below in Strings.xml and activity_main.xml
<string name="imgDescription">Background Picture</string>
you image will be like that:
<ImageView
android:id="@+id/imageView2"
android:lay`enter code hereout_width="0dp"
android:layout_height="wrap_content"
android:contentDescription="@string/imgDescription"
app:layout_editor_absoluteX="0dp"
app:layout_editor_absoluteY="0dp"
app:srcCompat="@drawable/background1"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp" />
android:contentDescription="@string/imgDescription"
Strings.xml
<resources>
<string name="app_name">Saini_Browser</string>
<string name="SainiBrowser">textView2</string>
<string name="imgDescription">BackGround Picture</string>
</resources>
If you're running PHP, I recommend Minify because it does combines and minifies on the fly for both CSS and JS. Once you've configured it, just work as normal and it takes care of everything.
Here is (low and dirty) workaround in case you need to use ajax or some feature which you cannot use when making link manually (using tag):
<%= Html.ActionLink("LinkTextToken", "ActionName", "ControllerName").ToHtmlString().Replace("LinkTextToken", "Refresh <span class='large sprite refresh'></span>")%>
You can use any text instead of 'LinkTextToken', it is there only to be replaced, it is only important that it does not occur anywhere else inside actionlink.
I have tried the following command on Ubuntu and its working for me
sudo apt-get install php7.0-mysql
Thanks
I am try to convert Object type variable into string using this line of code
try this to convert object value to string:
Java Code
Object dataobject=value;
//convert object into String
String convert= String.valueOf(dataobject);
Adding the data-position="fixed" and adding the below style in the css will fix the issue z-index: 1;
Note - if you want to pass a data attribute to a React Component, you need to handle them a little differently than other props.
2 options
Don't use camel case
<Option data-img-src='value' ... />
And then in the component, because of the dashes, you need to refer to the prop in quotes.
// @flow
class Option extends React.Component {
props: {
'data-img-src': string
}
And when you refer to it later, you don't use the dot syntax
render () {
return (
<option data-img-src={this.props['data-img-src']} >...</option>
)
}
}
Or use camel case
<Option dataImgSrc='value' ... />
And then in the component, you need to convert.
// @flow
class Option extends React.Component {
props: {
dataImgSrc: string
}
And when you refer to it later, you don't use the dot syntax
render () {
return (
<option data-img-src={this.props.dataImgSrc} >...</option>
)
}
}
Mainly just realize data-
attributes and aria-
attributes are treated specially. You are allowed to use hyphens in the attribute name in those two cases.
I tried a lot of plugins, most of them don't support all browsers, I prefer iScroll and nanoScroller works for all these browsers :
But iScroll do not work with touch!
demo iScroll : http://lab.cubiq.org/iscroll/examples/simple/
demo nanoScroller : http://jamesflorentino.github.io/nanoScrollerJS/
In normally html5 video player will support mp4, WebM, 3gp and OGV format directly.
<video controls>
<source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm>
<source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg>
<source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4>
<source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp>
</video>
We can add an external HLS js script in web application.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Your title</title>
<link href="https://unpkg.com/video.js/dist/video-js.css" rel="stylesheet">
<script src="https://unpkg.com/video.js/dist/video.js"></script>
<script src="https://unpkg.com/videojs-contrib-hls/dist/videojs-contrib-hls.js"></script>
</head>
<body>
<video id="my_video_1" class="video-js vjs-fluid vjs-default-skin" controls preload="auto"
data-setup='{}'>
<source src="https://cdn3.wowza.com/1/ejBGVnFIOW9yNlZv/cithRSsv/hls/live/playlist.m3u8" type="application/x-mpegURL">
</video>
<script>
var player = videojs('my_video_1');
player.play();
</script>
</body>
</html>
As of year 2020, JetBrains suggests to commit the .idea
folder.
The JetBrains IDEs (webstorm, intellij, android studio, pycharm, clion, etc.) automatically add that folder to your git repository (if there's one).
Inside the folder .idea
, has been already created a .gitignore
, updated by the IDE itself to avoid to commit user related settings that may contains privacy/password data.
It is safe (and usually useful) to commit the .idea
folder.
the method TextView.setTextSize(int unit , float size);
takes two parameters .
Try this :
text.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
UPDATE:
Now the setTextSize(float size)
will set the text size automatically in "scaled pixel
" units. no need to mention the COMPLEX_UNIT_SP manually.
Refer to the documentation.
I have just copied and moved a Magento site to a local area so I could work on it offline and had the same problem.
But in the end I found out Magento was forcing a redirect from http to https and I didn't have a SSL setup. So this solved my problem http://www.magentocommerce.com/wiki/recover/ssl_access_with_phpmyadmin
It pretty much says set web/secure/use_in_adminhtml value from 1 to 0 in the core_config_data to allow non-secure access to the admin area
Look at this awesome new library which is available via gradle :)
build.gradle: compile 'com.apptakk.http_request:http-request:0.1.2'
Usage:
new HttpRequestTask(
new HttpRequest("http://httpbin.org/post", HttpRequest.POST, "{ \"some\": \"data\" }"),
new HttpRequest.Handler() {
@Override
public void response(HttpResponse response) {
if (response.code == 200) {
Log.d(this.getClass().toString(), "Request successful!");
} else {
Log.e(this.getClass().toString(), "Request unsuccessful: " + response);
}
}
}).execute();
I think using UPDATE ... WHERE
as explained here and here is a lean approach
Project.update(
{ title: 'a very different title no' } /* set attributes' value */,
{ where: { _id : 1 }} /* where criteria */
).then(function(affectedRows) {
Project.findAll().then(function(Projects) {
console.log(Projects)
})
I'm not sure if this functionality is new, but you can also use the get_legend_handles_labels() method rather than keeping track of lines and labels yourself:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')
pi = np.pi
# fake data
time = np.linspace (0, 25, 50)
temp = 50 / np.sqrt (2 * pi * 3**2) \
* np.exp (-((time - 13)**2 / (3**2))**2) + 15
Swdown = 400 / np.sqrt (2 * pi * 3**2) * np.exp (-((time - 13)**2 / (3**2))**2)
Rn = Swdown - 10
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
ax2.plot(time, temp, '-r', label = 'temp')
# ask matplotlib for the plotted objects and their labels
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc=0)
ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()
There isn't a direct 1:1 equivalent.
You can password protect a folder or file using file system permissions. If you are using ASP.Net you can also use some of its built in functions to protect various urls.
If you are trying to port .htaccess files used for url rewriting, check out ISAPI Rewrite: http://www.isapirewrite.com/
You may want to look at IBExpert Personal Edition. While not open source, this is a very good tool for designing, building, and administering Firebird and InterBase databases.
The Personal Edition is free, but some of the more advanced features are not available. Still, even without the slick extras, the free version is very powerful.
Do not use the *
selector as that will apply to all elements on the page. Suppose you have a structure like this:
...
<body>
<div id="content">
<b>This is the main container.</b>
</div>
</body>
</html>
You can then center the #content
div using:
#content {
width: 400px;
margin: 0 auto;
background-color: #66ffff;
}
Don't know what you've seen elsewhere but this is the way to go. The * { margin: 0; padding: 0; }
snippet you've seen is for resetting browser's default definitions for all browsers to make your site behave similarly on all browsers, this has nothing to do with centering the main container.
Most browsers apply a default margin and padding to some elements which usually isn't consistent with other browsers' implementations. This is why it is often considered smart to use this kind of 'resetting'. The reset snippet you presented is the most simplest of reset stylesheets, you can read more about the subject here:
You need to add two new file one is index.html, copy and paste the below code and other is imageup.php which will upload your image
<form action="imageup.php" method="post" enctype="multipart/form-data">
<input type="file" name="banner" >
<input type="submit" value="submit">
</form>
imageup.php
<?php
$banner=$_FILES['banner']['name'];
$expbanner=explode('.',$banner);
$bannerexptype=$expbanner[1];
date_default_timezone_set('Australia/Melbourne');
$date = date('m/d/Yh:i:sa', time());
$rand=rand(10000,99999);
$encname=$date.$rand;
$bannername=md5($encname).'.'.$bannerexptype;
$bannerpath="uploads/banners/".$bannername;
move_uploaded_file($_FILES["banner"]["tmp_name"],$bannerpath);
?>
The above code will upload your image with encrypted name
system("pause");
is wrong because it's part of Windows API and so it won't work in other operation systems.
You should try to use just objects from C++ standard library. A better solution will be to write:
cin.get();
return 0;
But it will also cause problems if you have other cin
s in your code. Because after each cin
, you'll tap an Enter
or \n
which is a white space character. cin
ignores this character and leaves it in the buffer zone but cin.get()
, gets this remained character. So the control of the program reaches the line return 0
and the console gets closed before letting you see the results.
To solve this, we write the code as follows:
cin.ignore();
cin.get();
return 0;
Start > Computer : Properties > Change Settings > Advanced > Environment Variables > PATH : Edit [add this string (without "") at the end of line ";C:\<path to php folder>\php5.5.3"
].. open cmd and type composer
thats it :-)
If you are using Android studio, just edit the gradle.properties in the root folder and add android.useDeprecatedNdk=true. Then edit the build.gradle file in your app's folder, set abiFilters as below:
android {
....
defaultConfig {
....
ndk {
abiFilters "armeabi", "armeabi-v7a", "x86", "mips"
}
}
}
Might be wrong but:
Tinyint is an integer between 0 and 255
bit is either 1 or 0
Therefore to me bit is the choice for booleans
To get the child process and thread,
pstree -p PID
.
It also show the hierarchical tree
You can use .is(':visible')
to test if something is visible and .is(':hidden')
to test for the opposite:
$('#offers').toggle(!$('#column-left form').is(':visible')); // or:
$('#offers').toggle($('#column-left form').is(':hidden'));
Reference:
I solved this rather easily (without adding a method) so i'll share:
use Doctrine\Common\Collections\Criteria;
$repository->matching( Criteria::create()->where( Criteria::expr()->neq('id', 1) ) );
By the way, i'm using the Doctrine ORM module from within Zend Framework 2 and i'm not sure whether this would be compatible in any other case.
In my case, i was using a form element configuration like this: to show all roles except "guest" in a radio button array.
$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectRadio',
'name' => 'roles',
'options' => array(
'label' => _('Roles'),
'object_manager' => $this->getEntityManager(),
'target_class' => 'Application\Entity\Role',
'property' => 'roleId',
'find_method' => array(
'name' => 'matching',
'params' => array(
'criteria' => Criteria::create()->where(
Criteria::expr()->neq('roleId', 'guest')
),
),
),
),
));
I believe I found the solution in the jQuery documentation:
Animates all paragraph to a left style of 50 and opacity of 1 (opaque, visible), completing the animation within 500 milliseconds. It also will do it outside the queue, meaning it will automatically start without waiting for its turn.
$( "p" ).animate({ left: "50px", opacity: 1 }, { duration: 500, queue: false });
simply add: queue: false
.
For the former, convention over configuration. Rails default when you reference another table with
belongs_to :something
is to look for something_id
.
references
, or belongs_to
is actually newer way of writing the former with few quirks.
Important is to remember that it will not create foreign keys for you. In order to do that, you need to set it up explicitly using either:
t.references :something, foreign_key: true
t.belongs_to :something_else, foreign_key: true
or (note the plural):
add_foreign_key :table_name, :somethings
add_foreign_key :table_name, :something_elses`
You can create lib folder inside app you press right click and select directory you named as libs its will be worked
Bravo JSP Editor (Can't comment on how good it is, i haven't tried it) http://marketplace.eclipse.org/content/bravo-jsp-editor
This works:
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots(1,1)
x1 = [0,1,2,3]
squad = ['Fultz','Embiid','Dario','Simmons']
ax1.set_xticks(x1)
ax1.set_xticklabels(squad, minor=False, rotation=45)
You can do that way on a dict, not on a list. In a list elements are in sequence. In a dict they depend only on the index.
Simple code just to explain it by doing:
>>> lst = ['a','b','c']
>>> dct = {0: 'a', 1: 'b', 2:'c'}
>>> lst[0]
'a'
>>> dct[0]
'a'
>>> del lst[0]
>>> del dct[0]
>>> lst[0]
'b'
>>> dct[0]
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
dct[0]
KeyError: 0
>>> dct[1]
'b'
>>> lst[1]
'c'
A way to "convert" a list in a dict is:
>>> dct = {}
>>> for i in xrange(0,len(lst)): dct[i] = lst[i]
The inverse is:
lst = [dct[i] for i in sorted(dct.keys())]
Anyway I think it's better to start deleting from the higher index as you said.
This may have changed in Ruby 2.0
When I do this I get a fraction. For example on the console (either irb or rails c)
2.0.0-p195 :005 > require 'date'
=> true
2.0.0-p195 :006 > a_date = Date.parse("25/12/2013")
=> #<Date: 2013-12-25 ((2456652j,0s,0n),+0s,2299161j)>
2.0.0-p195 :007 > b_date = Date.parse("10/12/2013")
=> #<Date: 2013-12-10 ((2456637j,0s,0n),+0s,2299161j)>
2.0.0-p195 :008 > a_date-b_date
=> (15/1)
Of course, casting to an int give the expected result
2.0.0-p195 :009 > (a_date-b_date).to_i
=> 15
This also works for DateTime objects, but you have to take into consideration seconds, such as this example
2.0.0-p195 :017 > a_date_time = DateTime.now
=> #<DateTime: 2013-12-31T12:23:03-08:00 ((2456658j,73383s,725757000n),-28800s,2299161j)>
2.0.0-p195 :018 > b_date_time = DateTime.now-20
=> #<DateTime: 2013-12-11T12:23:06-08:00 ((2456638j,73386s,69998000n),-28800s,2299161j)>
2.0.0-p195 :019 > a_date_time - b_date_time
=> (1727997655759/86400000000)
2.0.0-p195 :020 > (a_date_time - b_date_time).to_i
=> 19
2.0.0-p195 :021 > c_date_time = a_date_time-20
=> #<DateTime: 2013-12-11T12:23:03-08:00 ((2456638j,73383s,725757000n),-28800s,2299161j)>
2.0.0-p195 :022 > a_date_time - c_date_time
=> (20/1)
2.0.0-p195 :023 > (a_date_time - c_date_time).to_i
=> 20
Intercept the KeyPressed event is in my opinion a good solid solution. Pay attention to trigger code characters (e.KeyChar lower then 32) if you use a RegExp.
But in this way is still possible to inject characters out of range whenever the user paste text from the clipboard. Unfortunately I did not found correct clipboard events to fix this.
So a waterproof solution is to intercept TextBox.TextChanged. Here is sometimes the original out of range character visible, for a short time. I recommend to implement both.
using System.Text.RegularExpressions;
private void Form1_Shown(object sender, EventArgs e)
{
filterTextBoxContent(textBox1);
}
string pattern = @"[^0-9^+^\-^/^*^(^)]";
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.KeyChar >= 32 && Regex.Match(e.KeyChar.ToString(), pattern).Success) { e.Handled = true; }
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
filterTextBoxContent(textBox1);
}
private bool filterTextBoxContent(TextBox textBox)
{
string text = textBox.Text;
MatchCollection matches = Regex.Matches(text, pattern);
bool matched = false;
int selectionStart = textBox.SelectionStart;
int selectionLength = textBox.SelectionLength;
int leftShift = 0;
foreach (Match match in matches)
{
if (match.Success && match.Captures.Count > 0)
{
matched = true;
Capture capture = match.Captures[0];
int captureLength = capture.Length;
int captureStart = capture.Index - leftShift;
int captureEnd = captureStart + captureLength;
int selectionEnd = selectionStart + selectionLength;
text = text.Substring(0, captureStart) + text.Substring(captureEnd, text.Length - captureEnd);
textBox.Text = text;
int boundSelectionStart = selectionStart < captureStart ? -1 : (selectionStart < captureEnd ? 0 : 1);
int boundSelectionEnd = selectionEnd < captureStart ? -1 : (selectionEnd < captureEnd ? 0 : 1);
if (boundSelectionStart == -1)
{
if (boundSelectionEnd == 0)
{
selectionLength -= selectionEnd - captureStart;
}
else if (boundSelectionEnd == 1)
{
selectionLength -= captureLength;
}
}
else if (boundSelectionStart == 0)
{
if (boundSelectionEnd == 0)
{
selectionStart = captureStart;
selectionLength = 0;
}
else if (boundSelectionEnd == 1)
{
selectionStart = captureStart;
selectionLength -= captureEnd - selectionStart;
}
}
else if (boundSelectionStart == 1)
{
selectionStart -= captureLength;
}
leftShift++;
}
}
textBox.SelectionStart = selectionStart;
textBox.SelectionLength = selectionLength;
return matched;
}
It sounds like you're using an incorrect address:
To access the Service I enter http://localhost/project/myService.svc/FileUpload
Assuming you mean this is the address you give your client code then I suspect it should actually be:
http://localhost/project/myService.svc
Erik's answer doesn't work on Windows Phone as is. The following does:
class WebClientEx : WebClient
{
private WebResponse m_Resp = null;
protected override WebResponse GetWebResponse(WebRequest Req, IAsyncResult ar)
{
try
{
this.m_Resp = base.GetWebResponse(request);
}
catch (WebException ex)
{
if (this.m_Resp == null)
this.m_Resp = ex.Response;
}
return this.m_Resp;
}
public HttpStatusCode StatusCode
{
get
{
if (m_Resp != null && m_Resp is HttpWebResponse)
return (m_Resp as HttpWebResponse).StatusCode;
else
return HttpStatusCode.OK;
}
}
}
At least it does when using OpenReadAsync
; for other xxxAsync
methods, careful testing would be highly recommended. The framework calls GetWebResponse somewhere along the code path; all one needs to do is capture and cache the response object.
The fallback code is 200 in this snippet because genuine HTTP errors - 500, 404, etc - are reported as exceptions anyway. The purpose of this trick is to capture non-error codes, in my specific case 304 (Not modified). So the fallback assumes that if the status code is somehow unavailable, at least it's a non-erroneous one.
I think I found exactly what you need. It may help others.
You can use the method UrlEncodedFormEntity.writeTo(OutputStream).
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvp);
http.connect();
OutputStream output = null;
try {
output = http.getOutputStream();
formEntity.writeTo(output);
} finally {
if (output != null) try { output.close(); } catch (IOException ioe) {}
}
The %
operator is for integers. You're looking for the fmod()
function.
#include <cmath>
int main()
{
double x = 6.3;
double y = 2.0;
double z = std::fmod(x,y);
}
I think that this is equivalent to asking if ToList does a deep or shallow copy. As ToList has no way to clone MyObject, it must do a shallow copy, so the created list contains the same references as the original one, so the code returns 5.
TL;DR: Use StandardError
instead for general exception catching. When the original exception is re-raised (e.g. when rescuing to log the exception only), rescuing Exception
is probably okay.
Exception
is the root of Ruby's exception hierarchy, so when you rescue Exception
you rescue from everything, including subclasses such as SyntaxError
, LoadError
, and Interrupt
.
Rescuing Interrupt
prevents the user from using CTRLC to exit the program.
Rescuing SignalException
prevents the program from responding correctly to signals. It will be unkillable except by kill -9
.
Rescuing SyntaxError
means that eval
s that fail will do so silently.
All of these can be shown by running this program, and trying to CTRLC or kill
it:
loop do
begin
sleep 1
eval "djsakru3924r9eiuorwju3498 += 5u84fior8u8t4ruyf8ihiure"
rescue Exception
puts "I refuse to fail or be stopped!"
end
end
Rescuing from Exception
isn't even the default. Doing
begin
# iceberg!
rescue
# lifeboats
end
does not rescue from Exception
, it rescues from StandardError
. You should generally specify something more specific than the default StandardError
, but rescuing from Exception
broadens the scope rather than narrowing it, and can have catastrophic results and make bug-hunting extremely difficult.
If you have a situation where you do want to rescue from StandardError
and you need a variable with the exception, you can use this form:
begin
# iceberg!
rescue => e
# lifeboats
end
which is equivalent to:
begin
# iceberg!
rescue StandardError => e
# lifeboats
end
One of the few common cases where it’s sane to rescue from Exception
is for logging/reporting purposes, in which case you should immediately re-raise the exception:
begin
# iceberg?
rescue Exception => e
# do some logging
raise # not enough lifeboats ;)
end
I created a VB script and run it either from command line or from a Java process. I also tried to catch errors when creating the shortcut so I can have a better error handling.
Set oWS = WScript.CreateObject("WScript.Shell")
shortcutLocation = Wscript.Arguments(0)
'error handle shortcut creation
On Error Resume Next
Set oLink = oWS.CreateShortcut(shortcutLocation)
If Err Then WScript.Quit Err.Number
'error handle setting shortcut target
On Error Resume Next
oLink.TargetPath = Wscript.Arguments(1)
If Err Then WScript.Quit Err.Number
'error handle setting start in property
On Error Resume Next
oLink.WorkingDirectory = Wscript.Arguments(2)
If Err Then WScript.Quit Err.Number
'error handle saving shortcut
On Error Resume Next
oLink.Save
If Err Then WScript.Quit Err.Number
I run the script with the following commmand:
cscript /b script.vbs shortcutFuturePath targetPath startInProperty
It is possible to have it working even without setting the 'Start in' property in some cases.
It looks like you're missing the runner definition on your test class, that could be the cause:
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class BallTest {
...
}
i made a little change to this code to save entry of a radio button but unable to save the text which appears in text box after selecting the radio button.
the code is below:-
<!DOCTYPE html>
<html>
<head>
<style>
form * {
display: block;
margin: 10px;
}
</style>
<script language="Javascript" >
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' +
encodeURIComponent(text));
pom.setAttribute('download', filename);
pom.style.display = 'none';
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom);
}
</script>
</head>
<body>
<form onsubmit="download(this['name'].value, this['text'].value)">
<input type="text" name="name" value="test.txt">
<textarea rows=3 cols=50 name="text">PLEASE WRITE ANSWER HERE. </textarea>
<input type="radio" name="radio" value="Option 1" onclick="getElementById('problem').value=this.value;"> Option 1<br>
<input type="radio" name="radio" value="Option 2" onclick="getElementById('problem').value=this.value;"> Option 2<br>
<form onsubmit="download(this['name'].value, this['text'].value)">
<input type="text" name="problem" id="problem">
<input type="submit" value="SAVE">
</form>
</body>
</html>
On Linux, Unix, Git Bash, or Cygwin, try:
rm -f .git/index.lock
On Windows Command Prompt, try:
del .git\index.lock
For Windows:
From a PowerShell console opened as administrator, try
rm -Force ./.git/index.lock
If that does not work, you must kill all git.exe processes
taskkill /F /IM git.exe
SUCCESS: The process "git.exe" with PID 20448 has been terminated.
SUCCESS: The process "git.exe" with PID 11312 has been terminated.
SUCCESS: The process "git.exe" with PID 23868 has been terminated.
SUCCESS: The process "git.exe" with PID 27496 has been terminated.
SUCCESS: The process "git.exe" with PID 33480 has been terminated.
SUCCESS: The process "git.exe" with PID 28036 has been terminated. \
rm -Force ./.git/index.lock
height attribute has been deprecated in html 5. What I would do is create a border around the hr and increase the thickness of the border as such: hr style="border:solid 2px black;"
This is the fastest way I have found, inspired by @divingTobi's answer. All The answers based on xlrd, openpyxl or pandas are slow for me, as they all load the whole file first.
from zipfile import ZipFile
from bs4 import BeautifulSoup # you also need to install "lxml" for the XML parser
with ZipFile(file) as zipped_file:
summary = zipped_file.open(r'xl/workbook.xml').read()
soup = BeautifulSoup(summary, "xml")
sheets = [sheet.get("name") for sheet in soup.find_all("sheet")]
The API of HttpComponents has got changed. It works with the code below.
public static HttpClient getTestHttpClient() {
try {
SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy(){
@Override
public boolean isTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
return true;
}
}, new AllowAllHostnameVerifier());
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("https",8444, sf));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(registry);
return new DefaultHttpClient(ccm);
} catch (Exception e) {
e.printStackTrace();
return new DefaultHttpClient();
}
}
matches();
does not buffer, but find()
buffers. find()
searches to the end of the string first, indexes the result, and return the boolean value and corresponding index.
That is why when you have a code like
1:Pattern.compile("[a-z]");
2:Pattern.matcher("0a1b1c3d4");
3:int count = 0;
4:while(matcher.find()){
5:count++: }
At 4: The regex engine using the pattern structure will read through the whole of your code (index to index as specified by the regex[single character]
to find at least one match. If such match is found, it will be indexed then the loop will execute based on the indexed result else if it didn't do ahead calculation like which matches()
; does not. The while statement would never execute since the first character of the matched string is not an alphabet.
This piece of code worked for me. What I was missing was I was not passing 'this' in button action:
onPress={this._handlePress.bind(this)}>
--------------
_handlePress(event) {
console.log('Pressed!');
var username = this.state.username;
var password = this.state.password;
console.log(username);
console.log(password);
}
render() {
return (
<View style={styles.container}>
<TextInput
ref="usr"
style={{height: 40, borderColor: 'gray', borderWidth: 1 , marginTop: 10 , padding : 10 , marginLeft : 5 , marginRight : 5 }}
placeHolder= "Enter username "
placeholderTextColor = '#a52a2a'
returnKeyType = {"next"}
autoFocus = {true}
autoCapitalize = "none"
autoCorrect = {false}
clearButtonMode = 'while-editing'
onChangeText={(text) => {
this.setState({username:text});
}}
onSubmitEditing={(event) => {
this.refs.psw.focus();
}}
/>
<TextInput
ref="psw"
style={{height: 40, borderColor: 'gray', borderWidth: 1 , marginTop: 10,marginLeft : 5 , marginRight : 5}}
placeholder= "Enter password"
placeholderTextColor = '#a52a2a'
autoCapitalize = "none"
autoCorrect = {false}
returnKeyType = {'done'}
secureTextEntry = {true}
clearButtonMode = 'while-editing'
onChangeText={(text) => {
this.setState({password:text});
}}
/>
<Button
style={{borderWidth: 1, borderColor: 'blue'}}
onPress={this._handlePress.bind(this)}>
Login
</Button>
</View>
);``
}
}
If you would like to auto format on save just with Javascript source, add this one into Users Setting
(press Cmd, or Ctrl,):
"[javascript]": { "editor.formatOnSave": true }
Virtual box version 4.3.28 worked with Genymotion 2.5.2 for me. Nothing else seemed to work.
This question is often asked in interview to check whether candidate understands correct usage of collection classes and is aware of alternative solutions available.
HashMap
class is roughly equivalent to Hashtable
, except that it is non synchronized and permits nulls. (HashMap
allows null values as key and value whereas Hashtable
doesn't allow null
s).HashMap
does not guarantee that the order of the map will remain constant over time.HashMap
is non synchronized whereas Hashtable
is synchronized.HashMap
is fail-safe while the enumerator for the Hashtable
is not and throw ConcurrentModificationException
if any other Thread modifies the map structurally by adding or removing any element except Iterator
's own remove()
method. But this is not a guaranteed behavior and will be done by JVM on best effort.Note on Some Important Terms:
Hashtable
will have to acquire a lock on the object while others will wait for lock to be released.set
method since it doesn't modify the collection "structurally". However, if prior to calling set
, the collection has been modified structurally, IllegalArgumentException
will be thrown.HashMap
can be synchronized by
Map m = Collections.synchronizeMap(hashMap);
Map provides Collection views instead of direct support for iteration
via Enumeration objects. Collection views greatly enhance the
expressiveness of the interface, as discussed later in this section.
Map allows you to iterate over keys, values, or key-value pairs;
Hashtable
does not provide the third option. Map provides a safe way
to remove entries in the midst of iteration; Hashtable
did not.
Finally, Map fixes a minor deficiency in the Hashtable
interface.
Hashtable
has a method called contains, which returns true if the
Hashtable
contains a given value. Given its name, you'd expect this
method to return true if the Hashtable
contained a given key, because
the key is the primary access mechanism for a Hashtable
. The Map
interface eliminates this source of confusion by renaming the method
containsValue
. Also, this improves the interface's consistency —
containsValue
parallels containsKey
.
From CLI:
$ su - postgres
$ psql template1
template1=# CREATE USER tester WITH PASSWORD 'test_password';
template1=# GRANT ALL PRIVILEGES ON DATABASE "test_database" to tester;
template1=# \q
PHP (as tested on localhost, it works as expected):
$connString = 'port=5432 dbname=test_database user=tester password=test_password';
$connHandler = pg_connect($connString);
echo 'Connected to '.pg_dbname($connHandler);
You templatize your class based on an 'unsigned int'.
Example:
template <unsigned int N>
class MyArray
{
public:
private:
double data[N]; // Use N as the size of the array
};
int main()
{
MyArray<2> a1;
MyArray<2> a2;
MyArray<4> b1;
a1 = a2; // OK The arrays are the same size.
a1 = b1; // FAIL because the size of the array is part of the
// template and thus the type, a1 and b1 are different types.
// Thus this is a COMPILE time failure.
}
You could use lists()
:
test::where('id' ,'>' ,0)->lists('id')->toArray();
NOTE : Better if you define your models in Studly Case
format, e.g Test
.
You could also use get()
:
test::where('id' ,'>' ,0)->get('id');
UPDATE: (For versions >= 5.2)
The lists()
method was deprecated in the new versions >= 5.2
, now you could use pluck()
method instead :
test::where('id' ,'>' ,0)->pluck('id')->toArray();
NOTE: If you need a string, for example in a blade, you can use function without the toArray() part, like:
test::where('id' ,'>' ,0)->pluck('id');
I'm using bootstrap.
I used css parameters.
.table {
table-layout:fixed;
}
.table td {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
and bootstrap grid system parameters, like this.
<th class="col-sm-2">Name</th>
<td class="col-sm-2">hoge</td>
If the variable you are checking would be in the global scope you could do:
array_key_exists('v', $GLOBALS)
Can't you import it as a git project and then (if you have the m2eclipse installed) right click on the project in the Package Explorer > Maven
> Enable Dependency Management
?
With the advent of Django 1.7, there is now a new update_or_create
QuerySet method, which should do exactly what you want. Just be careful of potential race conditions if uniqueness is not enforced at the database level.
Example from the documentation:
obj, created = Person.objects.update_or_create(
first_name='John', last_name='Lennon',
defaults={'first_name': 'Bob'},
)
The
update_or_create
method tries to fetch an object from database based on the given kwargs. If a match is found, it updates the fields passed in thedefaults
dictionary.
Pre-Django 1.7:
Change the model field values as appropriate, then call .save()
to persist the changes:
try:
obj = Model.objects.get(field=value)
obj.field = new_value
obj.save()
except Model.DoesNotExist:
obj = Model.objects.create(field=new_value)
# do something else with obj if need be
You might use Form
tag with action attribute to submit the mailto
.
Here is an example:
<form method="post" action="mailto:[email protected]" >
<input type="submit" value="Send Email" />
</form>
If the DNS server is configured properly, you won't be able to get the entire domain. If for some reason is allows zone transfers from any host, you'll have to send it the correct packet to make that request. I suspect that's what the dig statement you included does.
Below Function Perfectly Working on iOS7 or later version in Swift
func DeviceName()-> String {
var myDeviceName : String = String()
var systemInfo = [UInt8](count: sizeof(utsname), repeatedValue: 0)
let model = systemInfo.withUnsafeMutableBufferPointer { (inout body: UnsafeMutableBufferPointer<UInt8>) -> String? in
if uname(UnsafeMutablePointer(body.baseAddress)) != 0 {
return nil
}
return String.fromCString(UnsafePointer(body.baseAddress.advancedBy(Int(_SYS_NAMELEN * 4))))
}
let deviceNamesByCode : [String: String] = ["iPod1,1":"iPod Touch 1",
"iPod2,1":"iPod Touch 2",
"iPod3,1":"iPod Touch 3",
"iPod4,1":"iPod Touch 4",
"iPod5,1":"iPod Touch 5",
"iPod7,1":"iPod Touch 6",
"iPhone1,1":"iPhone",
"iPhone1,2":"iPhone ",
"iPhone2,1":"iPhone ",
"iPhone3,1":"iPhone 4",
"iPhone3,2":"iPhone 4",
"iPhone3,3":"iPhone 4",
"iPhone4,1":"iPhone 4s",
"iPhone5,1":"iPhone 5",
"iPhone5,2":"iPhone 5",
"iPhone5,3":"iPhone 5c",
"iPhone5,4":"iPhone 5c",
"iPhone6,1":"iPhone 5s",
"iPhone6,2":"iPhone 5s",
"iPhone7,2":"iPhone 6",
"iPhone7,1":"iPhone 6 Plus",
"iPhone8,1":"iPhone 6s",
"iPhone8,2":"iPhone 6s Plus",
"iPhone8,4":"iPhone SE",
"iPad2,1":"iPad 2",
"iPad2,2":"iPad 2",
"iPad2,3":"iPad 2",
"iPad2,4":"iPad 2",
"iPad3,1":"iPad 3",
"iPad3,2":"iPad 3",
"iPad3,3":"iPad 3",
"iPad3,4":"iPad 4",
"iPad3,5":"iPad 4",
"iPad3,6":"iPad 4",
"iPad4,1":"iPad Air",
"iPad4,2":"iPad Air",
"iPad4,3":"iPad Air",
"iPad5,3":"iPad Air 2",
"iPad5,4":"iPad Air 2",
"iPad2,5":"iPad Mini",
"iPad2,6":"iPad Mini",
"iPad2,7":"iPad Mini",
"iPad4,4":"iPad Mini 2",
"iPad4,5":"iPad Mini 2",
"iPad4,6":"iPad Mini 2",
"iPad4,7":"iPad Mini 3",
"iPad4,8":"iPad Mini 3",
"iPad4,9":"iPad Mini 3",
"iPad5,1":"iPad Mini 4",
"iPad5,2":"iPad Mini 4",
"iPad6,3":"iPad Pro",
"iPad6,4":"iPad Pro",
"iPad6,7":"iPad Pro",
"iPad6,8":"iPad Pro",
"AppleTV5,3":"Apple TV",
"i386":"Simulator",
"x86_64":"Simulator"
]
if model!.characters.count > 0 {
myDeviceName = deviceNamesByCode[model!]!
}else{
myDeviceName = UIDevice.currentDevice().model
}
print("myDeviceName==\(myDeviceName)")
return myDeviceName
}
I use POST when I don't want people to see the QueryString or when the QueryString gets large. Also, POST is needed for file uploads.
I don't see a problem using GET though, I use it for simple things where it makes sense to keep things on the QueryString.
Using GET will allow linking to a particular page possible too where POST would not work.
ALTER TABLE [dbo].[Employee] ADD DEFAULT ('N') FOR [CityBorn]
Your code doesn't do what you might think it does. Async methods return immediately after the method begins waiting for the async result. It's insightful to use tracing in order to investigate how the code is actually behaving.
The code below does the following:
static TypeHashes _type = new TypeHashes(typeof(Program));
private void Run()
{
TracerConfig.Reset("debugoutput");
using (Tracer t = new Tracer(_type, "Run"))
{
for (int i = 0; i < 4; i++)
{
DoSomeThingAsync(i);
}
}
Application.Run(); // Start window message pump to prevent termination
}
private async void DoSomeThingAsync(int i)
{
using (Tracer t = new Tracer(_type, "DoSomeThingAsync"))
{
t.Info("Hi in DoSomething {0}",i);
try
{
int result = await Calculate(i);
t.Info("Got async result: {0}", result);
}
catch (ArgumentException ex)
{
t.Error("Got argument exception: {0}", ex);
}
}
}
Task<int> Calculate(int i)
{
var t = new Task<int>(() =>
{
using (Tracer t2 = new Tracer(_type, "Calculate"))
{
if( i % 2 == 0 )
throw new ArgumentException(String.Format("Even argument {0}", i));
return i++;
}
});
t.Start();
return t;
}
When you observe the traces
22:25:12.649 02172/02820 { AsyncTest.Program.Run
22:25:12.656 02172/02820 { AsyncTest.Program.DoSomeThingAsync
22:25:12.657 02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 0
22:25:12.658 02172/05220 { AsyncTest.Program.Calculate
22:25:12.659 02172/02820 { AsyncTest.Program.DoSomeThingAsync
22:25:12.659 02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 1
22:25:12.660 02172/02756 { AsyncTest.Program.Calculate
22:25:12.662 02172/02820 { AsyncTest.Program.DoSomeThingAsync
22:25:12.662 02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 2
22:25:12.662 02172/02820 { AsyncTest.Program.DoSomeThingAsync
22:25:12.662 02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 3
22:25:12.664 02172/02756 } AsyncTest.Program.Calculate Duration 4ms
22:25:12.666 02172/02820 } AsyncTest.Program.Run Duration 17ms ---- Run has completed. The async methods are now scheduled on different threads.
22:25:12.667 02172/02756 Information AsyncTest.Program.DoSomeThingAsync Got async result: 1
22:25:12.667 02172/02756 } AsyncTest.Program.DoSomeThingAsync Duration 8ms
22:25:12.667 02172/02756 { AsyncTest.Program.Calculate
22:25:12.665 02172/05220 Exception AsyncTest.Program.Calculate Exception thrown: System.ArgumentException: Even argument 0
at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124
at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
22:25:12.668 02172/02756 Exception AsyncTest.Program.Calculate Exception thrown: System.ArgumentException: Even argument 2
at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124
at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
22:25:12.724 02172/05220 } AsyncTest.Program.Calculate Duration 66ms
22:25:12.724 02172/02756 } AsyncTest.Program.Calculate Duration 57ms
22:25:12.725 02172/05220 Error AsyncTest.Program.DoSomeThingAsync Got argument exception: System.ArgumentException: Even argument 0
Server stack trace:
at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124
at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
Exception rethrown at [0]:
at System.Runtime.CompilerServices.TaskAwaiter.EndAwait()
at System.Runtime.CompilerServices.TaskAwaiter`1.EndAwait()
at AsyncTest.Program.DoSomeThingAsyncd__8.MoveNext() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 106
22:25:12.725 02172/02756 Error AsyncTest.Program.DoSomeThingAsync Got argument exception: System.ArgumentException: Even argument 2
Server stack trace:
at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124
at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
Exception rethrown at [0]:
at System.Runtime.CompilerServices.TaskAwaiter.EndAwait()
at System.Runtime.CompilerServices.TaskAwaiter`1.EndAwait()
at AsyncTest.Program.DoSomeThingAsyncd__8.MoveNext() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 0
22:25:12.726 02172/05220 } AsyncTest.Program.DoSomeThingAsync Duration 70ms
22:25:12.726 02172/02756 } AsyncTest.Program.DoSomeThingAsync Duration 64ms
22:25:12.726 02172/05220 { AsyncTest.Program.Calculate
22:25:12.726 02172/05220 } AsyncTest.Program.Calculate Duration 0ms
22:25:12.726 02172/05220 Information AsyncTest.Program.DoSomeThingAsync Got async result: 3
22:25:12.726 02172/05220 } AsyncTest.Program.DoSomeThingAsync Duration 64ms
You will notice that the Run method completes on thread 2820 while only one child thread has finished (2756). If you put a try/catch around your await method you can "catch" the exception in the usual way although your code is executed on another thread when the calculation task has finished and your contiuation is executed.
The calculation method traces the thrown exception automatically because I did use the ApiChange.Api.dll from the ApiChange tool. Tracing and Reflector helps a lot to understand what is going on. To get rid of threading you can create your own versions of GetAwaiter BeginAwait and EndAwait and wrap not a task but e.g. a Lazy and trace inside your own extension methods. Then you will get much better understanding what the compiler and what the TPL does.
Now you see that there is no way to get in a try/catch your exception back since there is no stack frame left for any exception to propagate from. Your code might be doing something totally different after you did initiate the async operations. It might call Thread.Sleep or even terminate. As long as there is one foreground thread left your application will happily continue to execute asynchronous tasks.
You can handle the exception inside the async method after your asynchronous operation did finish and call back into the UI thread. The recommended way to do this is with TaskScheduler.FromSynchronizationContext. That does only work if you have an UI thread and it is not very busy with other things.
So its very simple way to achieve your task. You need to follow below step :-
1. First step
public interface APIService {
@Multipart
@POST("upload")
Call<ResponseBody> upload(
@Part("item") RequestBody description,
@Part("imageNumber") RequestBody description,
@Part MultipartBody.Part imageFile
);
}
You need to make the entire call as @Multipart request
. item
and image number
is just string body which is wrapped in RequestBody
. We use the MultipartBody.Part class
that allows us to send the actual file name besides the binary file data with the request
2. Second step
File file = (File) params[0];
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body =MultipartBody.Part.createFormData("Image", file.getName(), requestBody);
RequestBody ItemId = RequestBody.create(okhttp3.MultipartBody.FORM, "22");
RequestBody ImageNumber = RequestBody.create(okhttp3.MultipartBody.FORM,"1");
final Call<UploadImageResponse> request = apiService.uploadItemImage(body, ItemId,ImageNumber);
Now you have image path
and you need to convert into file
.Now convert file
into RequestBody
using method RequestBody.create(MediaType.parse("multipart/form-data"), file)
. Now you need to convert your RequestBody requestFile
into MultipartBody.Part
using method MultipartBody.Part.createFormData("Image", file.getName(), requestBody);
.
ImageNumber
and ItemId
is my another data which I need to send to server so I am also make both thing into RequestBody
.
Another solution (but it requires jQueryUI as pointed out by Richard Neil Ilagan in comments) :-
addClass, removeClass and toggleClass also accepts a second argument; the time duration to go from one state to the other.
$(this).addClass('abc',1000);
See jsfiddle:- http://jsfiddle.net/6hvZT/1/
Just to elaborate on Bhavin's excellent answer - editing the solution file works but you may still get the incompatible error (as David reported) if you had .NET 4.5 selected as the default .NET version in your VS2012 project and your VS2010 enviroment doesn't support that.
To quickly fix that, open the VS2012 .csproj file in a text editor and change the TargetFrameworkVersion down to 4.0 (from 4.5). VS2010 will then happily load the "edited" solution and projects.
You'll also have to edit an app.config files that have references to .NET 4.5 in a similar way to allow them to run on a .NET 4.0 environment.
After searching a solution for the same problem like you, I've found this small topic here. In advance I got a much smoother solution for this switch, case statement
switch($someString) #switch is caseINsensitive, so you don't need to lower
{
{ 'y' -or 'yes' } { "You entered Yes." }
default { "You entered No." }
}
From the structure of your source Object, I would try:
containerObject= new JSONObject(container);
if(containerObject.has("LabelData")){
JSONObject innerObject = containerObject.getJSONObject("LabelData");
if(innerObject.has("video")){
//Do with video
}
}
You can do this with Jinja's tojson
filter, which
Dumps a structure to JSON so that it’s safe to use in
<script>
tags [and] in any place in HTML with the notable exception of double quoted attributes.
For example, in your Python, write:
some_template.render(list_of_items=list_of_items)
... or, in the context of a Flask endpoint:
return render_template('your_template.html', list_of_items=list_of_items)
Then in your template, write this:
{% for item in list_of_items %}
<span onclick='somefunction({{item | tojson}})'>{{item}}</span><br>
{% endfor %}
(Note that the onclick
attribute is single-quoted. This is necessary since |tojson
escapes '
characters but not "
characters in its output, meaning that it can be safely used in single-quoted HTML attributes but not double-quoted ones.)
Or, to use list_of_items
in an inline script instead of an HTML attribute, write this:
<script>
const jsArrayOfItems = {{list_of_items | tojson}};
// ... do something with jsArrayOfItems in JavaScript ...
</script>
DON'T use json.dumps
to JSON-encode variables in your Python code and pass the resulting JSON text to your template. This will produce incorrect output for some string values, and will expose you to XSS if you're trying to encode user-provided values. This is because Python's built-in json.dumps
doesn't escape characters like <
and >
(which need escaping to safely template values into inline <script>
s, as noted at https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements) or single quotes (which need escaping to safely template values into single-quoted HTML attributes).
If you're using Flask, note that Flask injects a custom tojson
filter instead of using Jinja's version. However, everything written above still applies. The two versions behave almost identically; Flask's just allows for some app-specific configuration that isn't available in Jinja's version.
Thanks for your feed back got it to work I used the sshpass tool.
sshpass -p 'password' scp [email protected]:sys_config /var/www/dev/
It's important to note that there's no consensus on what's the best approach and related frameworks in general do not enforce nor reward certain structures.
I find this to be a frustrating and huge overhead but equally important. It is sort of a downplayed version (but IMO more important) of the style guide issue. I like to point this out because the answer is the same: it doesn't matter what structure you use as long as it's well defined and coherent.
So I'd propose to look for a comprehensive guide that you like and make it clear that the project is based on this.
It's not easy, especially if you're new to this! Expect to spend hours researching. You'll find most guides recommending an MVC-like structure. While several years ago that might have been a solid choice, nowadays that's not necessarily the case. For example here's another approach.
I've tested this solution and this works
mSubdomainEditText.setLongClickable(false);
mSubdomainEditText.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
public void onDestroyActionMode(ActionMode mode) {
}
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return false;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
});
Here is a function that even supports clockwise/anticlockwise drawing do that you control fills with the non-zero winding rule.
Here is a full article on how it works and more.
// Defines a path for any regular polygon with the specified number of sides and radius,
// centered on the provide x and y coordinates.
// optional parameters: startAngle and anticlockwise
function polygon(ctx, x, y, radius, sides, startAngle, anticlockwise) {
if (sides < 3) return;
var a = (Math.PI * 2)/sides;
a = anticlockwise?-a:a;
ctx.save();
ctx.translate(x,y);
ctx.rotate(startAngle);
ctx.moveTo(radius,0);
for (var i = 1; i < sides; i++) {
ctx.lineTo(radius*Math.cos(a*i),radius*Math.sin(a*i));
}
ctx.closePath();
ctx.restore();
}
// Example using the function.
// Define a path in the shape of a pentagon and then fill and stroke it.
context.beginPath();
polygon(context,125,125,100,5,-Math.PI/2);
context.fillStyle="rgba(227,11,93,0.75)";
context.fill();
context.stroke();
If you're an Azure DevOps user looking for both where and how to exclude files and folders, here ya go:
Example:
# Additional properties that will be passed to the scanner,
# Put one key=value per line, example:
# sonar.exclusions=**/*.bin
sonar.exclusions=MyProjectName/MyWebContentFolder/**
Note: If you're not sure on the path, you can go into sonarqube, view your project, look at all or new 'Code Smells' and the path you need is listed above each grouping of issues. You can grab the full path to a file or use wilds like these examples:
If you don't have the 'Run Code Analysis' task added, do that and place it somewhere after the 'Build solution **/*.sln' task.
Save and Queue and then check out your sonarqube server to see if the exclusions worked.
It's a permission problem.
When you run the console app, that app runs with your credentials, e.g. as "you".
The WCF service runs where? In IIS? Most likely, it runs under a separate account, which is not permissioned to query Active Directory.
You can either try to get the WCF impersonation thingie working, so that your own credentials get passed on, or you can specify a username/password on creating your DirectoryEntry:
DirectoryEntry directoryEntry =
new DirectoryEntry("LDAP://someserver.contoso.com/DC=contoso,DC=com",
userName, password);
OK, so it might not be the credentials after all (that's usually the case in over 80% of the cases I see).
What about changing your code a little bit?
DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry);
directorySearcher.Filter = string.Format("(&(objectClass=user)(objectCategory=user) (sAMAccountName={0}))", username);
directorySearcher.PropertiesToLoad.Add("msRTCSIP-PrimaryUserAddress");
var result = directorySearcher.FindOne();
if(result != null)
{
if(result.Properties["msRTCSIP-PrimaryUserAddress"] != null)
{
var resultValue = result.Properties["msRTCSIP-PrimaryUserAddress"][0];
}
}
My idea is: why not tell the DirectorySearcher
right off the bat what attribute you're interested in? Then you don't need to do another extra step to get the full DirectoryEntry
from the search result (should be faster), and since you told the directory searcher to find that property, it's certainly going to be loaded in the search result - so unless it's null (no value set), then you should be able to retrieve it easily.
Marc
Of course, just assign seperate css classes to both tables.
<table class="style1"></table>
<table class="style2"></table>
.css
table.style1 { //your css here}
table.style2 { //your css here}
It sounds like you want an out of source build. There are a couple of ways you can create an out of source build.
Do what you were doing, run
cd /path/to/my/build/folder
cmake /path/to/my/source/folder
which will cause cmake to generate a build tree in /path/to/my/build/folder
for the source tree in /path/to/my/source/folder
.
Once you've created it, cmake remembers where the source folder is - so you can rerun cmake on the build tree with
cmake /path/to/my/build/folder
or even
cmake .
if your current directory is already the build folder.
For CMake 3.13 or later, use these options to set the source and build folders
cmake -B/path/to/my/build/folder -S/path/to/my/source/folder
For older CMake, use some undocumented options to set the source and build folders:
cmake -B/path/to/my/build/folder -H/path/to/my/source/folder
which will do exactly the same thing as (1), but without the reliance on the current working directory.
CMake puts all of its outputs in the build tree by default, so unless you are liberally using ${CMAKE_SOURCE_DIR}
or ${CMAKE_CURRENT_SOURCE_DIR}
in your cmake files, it shouldn't touch your source tree.
The biggest thing that can go wrong is if you have previously generated a build tree in your source tree (i.e. you have an in source build). Once you've done this the second part of (1) above kicks in, and cmake doesn't make any changes to the source or build locations. Thus, you cannot create an out-of-source build for a source directory with an in-source build. You can fix this fairly easily by removing (at a minimum) CMakeCache.txt
from the source directory. There are a few other files (mostly in the CMakeFiles
directory) that CMake generates that you should remove as well, but these won't cause cmake to treat the source tree as a build tree.
Since out-of-source builds are often more desirable than in-source builds, you might want to modify your cmake to require out of source builds:
# Ensures that we do an out of source build
MACRO(MACRO_ENSURE_OUT_OF_SOURCE_BUILD MSG)
STRING(COMPARE EQUAL "${CMAKE_SOURCE_DIR}"
"${CMAKE_BINARY_DIR}" insource)
GET_FILENAME_COMPONENT(PARENTDIR ${CMAKE_SOURCE_DIR} PATH)
STRING(COMPARE EQUAL "${CMAKE_SOURCE_DIR}"
"${PARENTDIR}" insourcesubdir)
IF(insource OR insourcesubdir)
MESSAGE(FATAL_ERROR "${MSG}")
ENDIF(insource OR insourcesubdir)
ENDMACRO(MACRO_ENSURE_OUT_OF_SOURCE_BUILD)
MACRO_ENSURE_OUT_OF_SOURCE_BUILD(
"${CMAKE_PROJECT_NAME} requires an out of source build."
)
The above macro comes from a commonly used module called MacroOutOfSourceBuild
. There are numerous sources for MacroOutOfSourceBuild.cmake
on google but I can't seem to find the original and it's short enough to include here in full.
Unfortunately cmake has usually written a few files by the time the macro is invoked, so although it will stop you from actually performing the build you will still need to delete CMakeCache.txt
and CMakeFiles
.
You may find it useful to set the paths that binaries, shared and static libraries are written to - in which case see how do I make cmake output into a 'bin' dir? (disclaimer, I have the top voted answer on that question...but that's how I know about it).
You can use theme_get()
to display the possible options for theme.
You can control the legend font size using:
+ theme(legend.text=element_text(size=X))
replacing X with the desired size.
It sounds like you may be wanting to access the viewport of the device. You can do this by inserting this meta tag in your header.
<meta name="viewport" content="width=device-width, initial-scale=1.0">
time.clock()
was removed in Python 3.8 because it had platform-dependent behavior:
On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number
print(time.clock()); time.sleep(10); print(time.clock())
# Linux : 0.0382 0.0384 # see Processor Time
# Windows: 26.1224 36.1566 # see Wall-Clock Time
So which function to pick instead?
Processor Time: This is how long this specific process spends actively being executed on the CPU. Sleep, waiting for a web request, or time when only other processes are executed will not contribute to this.
time.process_time()
Wall-Clock Time: This refers to how much time has passed "on a clock hanging on the wall", i.e. outside real time.
Use time.perf_counter()
time.time()
also measures wall-clock time but can be reset, so you could go back in timetime.monotonic()
cannot be reset (monotonic = only goes forward) but has lower precision than time.perf_counter()
string input = "America.USA"
string output = input.Substring(input.IndexOf('.') + 1);
If an InterruptedException
is thrown it means that something wants to interrupt (usually terminate) that thread. This is triggered by a call to the threads interrupt()
method. The wait method detects that and throws an InterruptedException
so the catch code can handle the request for termination immediately and does not have to wait till the specified time is up.
If you use it in a single-threaded app (and also in some multi-threaded apps), that exception will never be triggered. Ignoring it by having an empty catch clause I would not recommend. The throwing of the InterruptedException
clears the interrupted state of the thread, so if not handled properly that info gets lost. Therefore I would propose to run:
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
// code for stopping current task so thread stops
}
Which sets that state again. After that, finish execution. This would be correct behaviour, even tough never used.
What might be better is to add this:
} catch (InterruptedException e) {
throw new RuntimeException("Unexpected interrupt", e);
}
...statement to the catch block. That basically means that it must never happen. So if the code is re-used in an environment where it might happen it will complain about it.
This is in the case if first answer does not work The latest version of git does not require to set proxy it directly uses system proxy settings .so just do these
unset HTTP_PROXY
unset HTTPS_PROXY
in some systems you may also have to do
unset http_proxy
unset https_proxy
if you want to permanantly remove proxy then
sudo gsettings set org.gnome.system.proxy mode 'none'
tl;dr version: use ~/.zshrc
And read the man page to understand the differences between:
~/.zshrc
,~/.zshenv
and~/.zprofile
.
In my comment attached to the answer kev gave, I said:
This seems to be incorrect - /etc/profile isn't listed in any zsh documentation I can find.
This turns out to be partially incorrect: /etc/profile
may be sourced by zsh
. However, this only occurs if zsh
is "invoked as sh
or ksh
"; in these compatibility modes:
The usual zsh startup/shutdown scripts are not executed. Login shells source /etc/profile followed by $HOME/.profile. If the ENV environment variable is set on invocation, $ENV is sourced after the profile scripts. The value of ENV is subjected to parameter expansion, command substitution, and arithmetic expansion before being interpreted as a pathname. [man zshall, "Compatibility"].
The ArchWiki ZSH link says:
At login, Zsh sources the following files in this order:
/etc/profile
This file is sourced by all Bourne-compatible shells upon login
This implys that /etc/profile
is always read by zsh
at login - I haven't got any experience with the Arch Linux project; the wiki may be correct for that distribution, but it is not generally correct. The information is incorrect compared to the zsh manual pages, and doesn't seem to apply to zsh on OS X (paths in $PATH
set in /etc/profile
do not make it to my zsh sessions).
where exactly should I be placing my rvm, python, node etc additions to my $PATH?
Generally, I would export my $PATH
from ~/.zshrc
, but it's worth having a read of the zshall man page, specifically the "STARTUP/SHUTDOWN FILES" section - ~/.zshrc
is read for interactive shells, which may or may not suit your needs - if you want the $PATH
for every zsh
shell invoked by you (both interactive
and not, both login
and not, etc), then ~/.zshenv
is a better option.
Is there a specific file I should be using (i.e. .zshenv which does not currently exist in my installation), one of the ones I am currently using, or does it even matter?
There's a bunch of files read on startup (check the linked man
pages), and there's a reason for that - each file has it's particular place (settings for every user, settings for user-specific, settings for login shells, settings for every shell, etc).
Don't worry about ~/.zshenv
not existing - if you need it, make it, and it will be read.
.bashrc
and .bash_profile
are not read by zsh
, unless you explicitly source them from ~/.zshrc
or similar; the syntax between bash
and zsh
is not always compatible. Both .bashrc
and .bash_profile
are designed for bash
settings, not zsh
settings.
Using Script Console.
In case the jobs are grouped it's possible to either give it a full name with forward slashes:
getItemByFullName("folder_name/job_name")
job.getBuilds().each { it.delete() }
job.nextBuildNumber = 1
job.save()
or traverse the hierarchy like this:
def folder = Jenkins.instance.getItem("folder_name")
def job = folder.getItem("job_name")
job.getBuilds().each { it.delete() }
job.nextBuildNumber = 1
job.save()
You seem to be misunderstanding how import
searches for modules. When you use an import statement it always searches the actual module path (and/or sys.modules
); it doesn't make use of module objects in the local namespace that exist because of previous imports. When you do:
import package.subpackage.module
from package.subpackage import module
from module import attribute1
The second line looks for a package called package.subpackage
and imports module
from that package. This line has no effect on the third line. The third line just looks for a module called module
and doesn't find one. It doesn't "re-use" the object called module
that you got from the line above.
In other words from someModule import ...
doesn't mean "from the module called someModule that I imported earlier..." it means "from the module named someModule that you find on sys.path...". There is no way to "incrementally" build up a module's path by importing the packages that lead to it. You always have to refer to the entire module name when importing.
It's not clear what you're trying to achieve. If you only want to import the particular object attribute1, just do from package.subpackage.module import attribute1
and be done with it. You need never worry about the long package.subpackage.module
once you've imported the name you want from it.
If you do want to have access to the module to access other names later, then you can do from package.subpackage import module
and, as you've seen you can then do module.attribute1
and so on as much as you like.
If you want both --- that is, if you want attribute1
directly accessible and you want module
accessible, just do both of the above:
from package.subpackage import module
from package.subpackage.module import attribute1
attribute1 # works
module.someOtherAttribute # also works
If you don't like typing package.subpackage
even twice, you can just manually create a local reference to attribute1:
from package.subpackage import module
attribute1 = module.attribute1
attribute1 # works
module.someOtherAttribute #also works
What you're trying to achieve is simple, and the way you're going about it isn't. Try this (Works fine for me) and save the file as a batch from your text editor. Trust me, it's easier.
start firefox.exe
You can also map the share to a local drive as follows:
net use X: "\\servername\share" /user:morgan password
include
folder where you have installed
Codeblocks. int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX,
in that line.ArrayList is faster than LinkedList if I randomly access its elements. I think random access means "give me the nth element". Why ArrayList is faster?
ArrayList
has direct references to every element in the list, so it can get the n-th element in constant time. LinkedList
has to traverse the list from the beginning to get to the n-th element.
LinkedList is faster than ArrayList for deletion. I understand this one. ArrayList's slower since the internal backing-up array needs to be reallocated.
ArrayList
is slower because it needs to copy part of the array in order to remove the slot that has become free. If the deletion is done using the ListIterator.remove()
API, LinkedList
just has to manipulate a couple of references; if the deletion is done by value or by index, LinkedList
has to potentially scan the entire list first to find the element(s) to be deleted.
If it means move some elements back and then put the element in the middle empty spot, ArrayList should be slower.
Yes, this is what it means. ArrayList
is indeed slower than LinkedList
because it has to free up a slot in the middle of the array. This involves moving some references around and in the worst case reallocating the entire array. LinkedList
just has to manipulate some references.
@SuppressLint({ "NewApi", "NewApi", "NewApi", "NewApi" })
@SuppressWarnings("deprecation")
@TargetApi(11)
public void onClickCopy(View v) { // User-defined onClick Listener
int sdk_Version = android.os.Build.VERSION.SDK_INT;
if(sdk_Version < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(textView.getText().toString()); // Assuming that you are copying the text from a TextView
Toast.makeText(getApplicationContext(), "Copied to Clipboard!", Toast.LENGTH_SHORT).show();
}
else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("Text Label", textView.getText().toString());
clipboard.setPrimaryClip(clip);
Toast.makeText(getApplicationContext(), "Copied to Clipboard!", Toast.LENGTH_SHORT).show();
}
}
cd %ProgramFiles%\SlikSvn\bin
https://github.com/ZeBobo5/Vlc.DotNet/tree/develop/src/Samples
tree/develop
or tree/master
with trunk
svn export https://github.com/ZeBobo5/Vlc.DotNet/trunk/src/Samples
Try this:
List<Double> l1= new ArrayList<Double>();
l1.add(1.38);
l1.add(2.56);
l1.add(4.3);
I bumped into the same issue, and I also had to make the ViewPager wrap around its contents when the user scrolled between the pages. Using cybergen's above answer, I defined the onMeasure method as following:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (getCurrentItem() < getChildCount()) {
View child = getChildAt(getCurrentItem());
if (child.getVisibility() != GONE) {
heightMeasureSpec = MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(heightMeasureSpec),
MeasureSpec.UNSPECIFIED);
child.measure(widthMeasureSpec, heightMeasureSpec);
}
setMeasuredDimension(getMeasuredWidth(), measureHeight(heightMeasureSpec, getChildAt(getCurrentItem())));
}
}
This way, the onMeasure method sets the height of the current page displayed by the ViewPager.
Restarting the adb server, Eclipse, and device did the trick for me.
C:\Android\android-sdk\platform-tools>adb kill-server
C:\Android\android-sdk\platform-tools>adb start-server
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
I had the same problem as mentioned on this question.
If you are using Eclipse,
They should all be in there. Right click and "checkout."
With GNU units
:
$ units
2411 units, 71 prefixes, 33 nonlinear units
You have: (10hr+36min+10s)-(10hr+33min+56s)
You want: s
* 134
/ 0.0074626866
You have: (10hr+36min+10s)-(10hr+33min+56s)
You want: min
* 2.2333333
/ 0.44776119
You can forget all other answers - there is a great generic solution: http://cleansharp.de/wordpress/2011/05/generischer-typeconverter/
This allows you to write very clean code like this:
string value = null;
int? x = value.ConvertOrDefault();
and also:
object obj = 1;
string value = null;
int x = 5;
if (value.TryConvert(out x))
Console.WriteLine("TryConvert example: " + x);
bool boolean = "false".ConvertOrDefault();
bool? nullableBoolean = "".ConvertOrDefault();
int integer = obj.ConvertOrDefault();
int negativeInteger = "-12123".ConvertOrDefault();
int? nullableInteger = value.ConvertOrDefault();
MyEnum enumValue = "SecondValue".ConvertOrDefault();
MyObjectBase myObject = new MyObjectClassA();
MyObjectClassA myObjectClassA = myObject.ConvertOrDefault();
rem = lambda x, unwanted : ''.join([ c for i, c in enumerate(x) if i != unwanted])
rem('1230004', 4)
'123004'
Have you tried RedirectToAction
?
For anyone running MySQL on Amazon RDS service, this change is done via parameter groups. You need to create a new PG or use an existing one (other than the default, which is read-only).
You should search for the max_allowed_packet
parameter, change its value, and then hit save.
Back in your MySQL instance, if you created a new PG, you should attach the PG to your instance (you may need a reboot). If you changed a PG that was already attached to your instance, changes will be applied without reboot, to all your instances that have that PG attached.
You can use this function to get the absolute value:
+(NSNumber *)absoluteValue:(NSNumber *)input {
return [NSNumber numberWithDouble:fabs([input doubleValue])];
}
SATELLITE
or HYBRID
well, it is just a watermark, you can hide it if you change the <div>
that has z-index=100
I use
setInterval(function(){
$("*").each(function() {
if ($(this).css("zIndex") == 100) {
$(this).css("zIndex", "-100");
}
})}
, 10);
or you can use
map.addListener('idle', function(e) {
//same function
}
but it is not as responsive as setInterval
At Sep 19 2018, these lines worked for me:
File-> Preferences -> Keyboard Shortcuts.
An editor will appear with keybindings.json file. Place the following JSON in there and save.
// Place your key bindings in this file to overwrite the defaults
[
{
"key": "ctrl+shift+u",
"command": "editor.action.transformToUppercase",
"when": "editorTextFocus"
},
{
"key": "ctrl+shift+l",
"command": "editor.action.transformToLowercase",
"when": "editorTextFocus"
},
]
Even if we interchange @Component or @Repository or @service
It will behave the same , but one aspect is that they wont be able to catch some specific exception related to DAO instead of Repository if we use component or @ service
Once you've converted your String to a number, you can use
// format the number for the default locale
NumberFormat.getInstance().format(num)
or
// format the number for a particular locale
NumberFormat.getInstance(locale).format(num)
This is default by iOS7 design. try to do the below:
[tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
You can set the 'Separator Inset' from the storyboard:
It can also be solved using quaternion theory:
def angle_axis_quat(theta, axis):
"""
Given an angle and an axis, it returns a quaternion.
"""
axis = np.array(axis) / np.linalg.norm(axis)
return np.append([np.cos(theta/2)],np.sin(theta/2) * axis)
def mult_quat(q1, q2):
"""
Quaternion multiplication.
"""
q3 = np.copy(q1)
q3[0] = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3]
q3[1] = q1[0]*q2[1] + q1[1]*q2[0] + q1[2]*q2[3] - q1[3]*q2[2]
q3[2] = q1[0]*q2[2] - q1[1]*q2[3] + q1[2]*q2[0] + q1[3]*q2[1]
q3[3] = q1[0]*q2[3] + q1[1]*q2[2] - q1[2]*q2[1] + q1[3]*q2[0]
return q3
def rotate_quat(quat, vect):
"""
Rotate a vector with the rotation defined by a quaternion.
"""
# Transfrom vect into an quaternion
vect = np.append([0],vect)
# Normalize it
norm_vect = np.linalg.norm(vect)
vect = vect/norm_vect
# Computes the conjugate of quat
quat_ = np.append(quat[0],-quat[1:])
# The result is given by: quat * vect * quat_
res = mult_quat(quat, mult_quat(vect,quat_)) * norm_vect
return res[1:]
v = [3, 5, 0]
axis = [4, 4, 1]
theta = 1.2
print(rotate_quat(angle_axis_quat(theta, axis), v))
# [2.74911638 4.77180932 1.91629719]
change the position absolute of div busy to fixed
Remove static
keyword in method definition. Keep it just in your class definition.
static
keyword placed in .cpp file means that a certain function has a static linkage, ie. it is accessible only from other functions in the same file.
Try using
DateTime.ParseExact(
txtPaymentSummaryBeginDate.Text.Trim(),
"MM/dd/yyyy",
System.Globalization.CultureInfo.InvariantCulture
);
It throws an exception if the input string is not in proper format, so in the catch
section you can return false;
If you have a pandas dataframe and want to preserve the dtypes, even the categoricals, this is a fast way to do it:
import numpy as np
import pandas as pd
df = pd.DataFrame({1: [1, 2, 3], 2: [4, 5, 6]})
number_repeats = 50
new_df = df.reindex(np.tile(df.index, number_repeats))
Laravel 7
Create a migration file using cli command:
php artisan make:migration add_paid_to_users_table --table=users
A file will be created in the migrations folder, open it in an editor.
Add to the function up():
Schema::table('users', function (Blueprint $table) {
// Create new column
// You probably want to make the new column nullable
$table->integer('paid')->nullable()->after('status');
}
Add to the function down(), this will run in case migration fails for some reasons:
$table->dropColumn('paid');
Run migration using cli command:
php artisan migrate
In case you want to add a column to the table to create a foreign key constraint:
In step 3 of the above process, you'll use the following code:
$table->bigInteger('address_id')->unsigned()->nullable()->after('tel_number');
$table->foreign('address_id')->references('id')->on('addresses')->onDelete('SET NULL');
In step 4 of the above process, you'll use the following code:
// 1. Drop foreign key constraints
$table->dropForeign(['address_id']);
// 2. Drop the column
$table->dropColumn('address_id');
Yes, it is possible since lists are mutable.
Look at the built-in enumerate()
function to get an idea how to iterate over the list and find each entry's index (which you can then use to assign to the specific list item).
I had the same problem as Daniel, setting the commit address and unsetting the credentials helper also worked for me.
git config --global user.email '<git-commit-address>'
git config --global --unset credential.helper
If you dont want to format a separate column with you normal dates pasted to it -- do the following -- add a column to the extreme left of your data and reverve your date ie if the date you had already entered was for example 11.5.16 enter int he new lefthand column 160511 ( notice that there are numbers only and no full stops . When you now sort there will be no mix ups as you have encountered.i have used this method for over 30 years and it never lets me down. And as you have placed the date by year, month and day you neednt include that column if you want or need tu print out your complete list.
Try this one
string redirect = "<script>window.open('http://www.google.com');</script>";
Response.Write(redirect);
I know angular has hierarchical injectors like Thierry said.
But I have another option here in case you find a use-case where you don't really want to inject it at the parent.
We can achieve that by creating an instance of the service, and on provide always return that.
import { provide, Injectable } from '@angular/core';
import { Http } from '@angular/core'; //Dummy example of dependencies
@Injectable()
export class YourService {
private static instance: YourService = null;
// Return the instance of the service
public static getInstance(http: Http): YourService {
if (YourService.instance === null) {
YourService.instance = new YourService(http);
}
return YourService.instance;
}
constructor(private http: Http) {}
}
export const YOUR_SERVICE_PROVIDER = [
provide(YourService, {
deps: [Http],
useFactory: (http: Http): YourService => {
return YourService.getInstance(http);
}
})
];
And then on your component you use your custom provide method.
@Component({
providers: [YOUR_SERVICE_PROVIDER]
})
And you should have a singleton service without depending on the hierarchical injectors.
I'm not saying this is a better way, is just in case someone has a problem where hierarchical injectors aren't possible.
In LINQ you could do something like:
foreach (var data in from DataRow row in dataTable.Rows
from DataColumn col in dataTable.Columns
where
row[col] != null
select row[col])
{
// do something with data
}
I you have the char '9'
, it will store its ASCII code, so to get the int value, you have 2 ways
char x = '9';
int y = Character.getNumericValue(x); //use a existing function
System.out.println(y + " " + (y + 1)); // 9 10
or
char x = '9';
int y = x - '0'; // substract '0' code to get the difference
System.out.println(y + " " + (y + 1)); // 9 10
And it fact, this works also :
char x = 9;
System.out.println(">" + x + "<"); //> < prints a horizontal tab
int y = (int) x;
System.out.println(y + " " + (y + 1)); //9 10
You store the 9
code, which corresponds to a horizontal tab
(you can see when print as String
, bu you can also use it as int
as you see above
If you want to click on all elements selected by some class, you can use this example (used on last.fm on the Loved tracks page to Unlove all).
var divs = document.querySelectorAll('.love-button.love-button--loved');
for (i = 0; i < divs.length; ++i) {
divs[i].click();
};
With ES6 and Babel (cannot be run in the browser console directly)
[...document.querySelectorAll('.love-button.love-button--loved')]
.forEach(div => { div.click(); })
You need to add the following line:
using FootballLeagueSystem;
into your all your classes (MainMenu.cs, programme.cs, etc.) that use Login
.
At the moment the compiler can't find the Login
class.
Login into the machine as oracle login user id( where oracle is installed)..
Add ORACLE_HOME = <Oracle installation Directory>
in Environment variable
Open a command prompt
Change the directory to %ORACLE_HOME%\bin
type the command sqlplus /nolog
SQL> connect /as sysdba
SQL> alter user SYS identified by "newpassword";
One more check, while oracle installation and database confiuration assistant setup, if you configure any database then you might have given password and checked the same password for all other accounts.. If so, then you try with the password which you have given in your database configuration assistant setup.
Hope this will work for you..
Try C# string interpolation introduced in C# 6:
var id = 100;
var hexid = $"0x{id:X}";
hexid value:
"0x64"
Chrome Version 50.0.2661.87 m does not support the mm-dd-yy format when assigned to a variable. It uses yy-mm-dd. IE and Firefox work as expected.
Here's an example using Angular 2+
For example, if you wanted to close a Modal Component if the user clicks outside of it:
// Close the modal if the document is clicked.
@HostListener('document:click', ['$event'])
public onDocumentClick(event: MouseEvent): void {
this.closeModal();
}
// Don't close the modal if the modal itself is clicked.
@HostListener('click', ['$event'])
public onClick(event: MouseEvent): void {
event.stopPropagation();
}
Advanced Conventional Formatting [Update]
XMLSpectrum is an open source syntax-highlighter. Supporting XML - but with special features for XSLT 2.0, XSD 1.1 and XPath 2.0. I'm mentioning this here because it also has special formatting capabilities for XML: it vertically aligns attributes and their contents as well as elements - to enhance XML readability.
The output HTML is suitable for reviewing in a browser or if the XML needs further editing it can be copied and pasted into an XML editor of your choice
Because xmlspectrum.xsl uses its own XML text parser, all content such as entity references and CDATA sections are preserved - as in an editor.
Note on usage: this is just an XSLT 2.0 stylesheet so you would need to enclose the required command-line (samples provided) in a small script so you could automatically transform the XML source.
Virtual Formatting
XMLQuire is a free XML editor that has special formatting capabilities - it formats XML properly, including multi-line attributes, attribute-values, word-wrap indentation and even XML comments.
All XML indentation is done without inserting tabs or spaces, ensuring the integrity of the XML is maintained. For versions of Windows later than XP, no installation is needed, its just a 3MB .exe file.
If you need to print out the formatted XML there are special options within the print-preview, such as line-numbering that follows the indentation. If you need to copy the formatted XML to a word processor as rich text, that's available too.
[Disclosure: I maintain both XMLQuire and XMLSpectrum as 'home projects']
Your not applying Date formator. rather you are just parsing the date. to get output in this format
yyyy-MM-dd HH:mm:ss.SSSSSS
we have to use format() method here is full example:-
Here is full example:-
it will take Date in this format yyyy-MM-dd HH:mm:ss.SSSSSS
and as result we will get output as same as this format yyyy-MM-dd HH:mm:ss.SSSSSS
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
//TODO OutPut should LIKE in this format yyyy-MM-dd HH:mm:ss.SSSSSS.
public class TestDateExample {
public static void main(String args[]) throws ParseException {
SimpleDateFormat changeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
java.util.Date temp = changeFormat.parse("2012-07-10 14:58:00.000000");
Date thisDate = changeFormat.parse("2012-07-10 14:58:00.000000");
System.out.println(thisDate);
System.out.println("----------------------------");
System.out.println("After applying formating :");
String strDateOutput = changeFormat.format(temp);
System.out.println(strDateOutput);
}
}
I have encoding problems with XMLFilter solution, so I made XMLStreamReader to ignore namespaces:
class XMLReaderWithoutNamespace extends StreamReaderDelegate {
public XMLReaderWithoutNamespace(XMLStreamReader reader) {
super(reader);
}
@Override
public String getAttributeNamespace(int arg0) {
return "";
}
@Override
public String getNamespaceURI() {
return "";
}
}
InputStream is = new FileInputStream(name);
XMLStreamReader xsr = XMLInputFactory.newFactory().createXMLStreamReader(is);
XMLReaderWithoutNamespace xr = new XMLReaderWithoutNamespace(xsr);
Unmarshaller um = jc.createUnmarshaller();
Object res = um.unmarshal(xr);
If you installed with brew, try brew uninstall yarn
at terminal prompt. Also remember to remove yarn path info in your .bash_profile
.
The problem is that you are calling ToString in a LINQ to Entities query. That means the parser is trying to convert the ToString call into its equivalent SQL (which isn't possible...hence the exception).
All you have to do is move the ToString call to a separate line:
var keyString = item.Key.ToString();
var pages = from p in context.entities
where p.Serial == keyString
select p;
When you #include
a header, it's exactly as if you put the code into the source file itself. In both cases the varGlobal
variable is defined in the source so it will work no matter how it's declared.
Also as pointed out in the comments, C++ variables at file scope are not static in scope even though they will be assigned to static storage. If the variable were a class member for example, it would need to be accessible to other compilation units in the program by default and non-class members are no different.
When converting an ASP.Net webform prototype to a MVC site I got these errors:
TypeError: $(...).accordion is not a function
$("#accordion").accordion(
$('#dialog').dialog({
TypeError: $(...).dialog is not a function
It worked fine in the webforms. The problem/solution was this line in the _Layout.cshtml
@Scripts.Render("~/bundles/jquery")
Comment it out to see if the errors go away. Then fix it in the BundlesConfig:
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
You can use it this way
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
child: Text(
'Card with circular border',
textScaleFactor: 1.2,
),
),
Card(
shape: BeveledRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
child: Text(
'Card with Beveled border',
textScaleFactor: 1.2,
),
),
Card(
shape: StadiumBorder(
side: BorderSide(
color: Colors.black,
width: 2.0,
),
),
child: Text(
'Card with Beveled border',
textScaleFactor: 1.2,
),
),
Particularly when using something like Twitter's Bootstrap, white-space: nowrap;
doesn't always work in CSS when applying padding or margin to a child div
. Instead however, adding an equivalent border: 20px solid transparent;
style in place of padding/margin works more consistently.
The top answer here created a 60px-high tag that was masking other links that stopped working as a result. I found this solution working without side-effects.
<a class="anchor" id="top"></a>
a.anchor {
display: block;
position: relative;
top: -60px;
visibility: hidden;
}
From MSDN:
Date and time data from January 1, 1753, to December 31, 9999, with an accuracy of one three-hundredth second, or 3.33 milliseconds. Values are rounded to increments of .000, .003, or .007 milliseconds. Stored as two 4-byte integers. The first 4 bytes store the number of days before or after the base date, January 1, 1900. The base date is the system's reference date. Values for datetime earlier than January 1, 1753, are not permitted. The other 4 bytes store the time of day represented as the number of milliseconds after midnight. Seconds have a valid range of 0–59.
SQL uses a different system than C# for DateTime values.
You can use your MinValue as a sentinel value - and if it is MinValue - pass null into your object (and store the date as nullable in the DB).
if(date == dateTime.Minvalue)
objinfo.BirthDate = null;
The simplest way (using Apache Common Codec):
byte[] bytes = Hex.decodeHex(str.toCharArray());
instead of using
ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(this).parentNode);
try using
ReactDOM.unmountComponentAtNode(document.getElementById('root'));
Go to Run configurations in your eclipse then -VM arguments add this: -Dlog4j.configuration=log4j-config_folder/log4j.xml
replace log4j-config_folder with your folder structure where you have your log4j.xml file
The trick is that you have to set it as position:fixed, but only after the user has scrolled past it.
This is done with something like this, attaching a handler to the window.scroll event
// Cache selectors outside callback for performance.
var $window = $(window),
$stickyEl = $('#the-sticky-div'),
elTop = $stickyEl.offset().top;
$window.scroll(function() {
$stickyEl.toggleClass('sticky', $window.scrollTop() > elTop);
});
This simply adds a sticky
CSS class when the page has scrolled past it, and removes the class when it's back up.
And the CSS class looks like this
#the-sticky-div.sticky {
position: fixed;
top: 0;
}
EDIT- Modified code to cache jQuery objects, faster now.
If you are targeting more modern browsers, life can be very simple. try:
.elem{
height: 100vh;
}
if you need it at 50% of the page, replace 100 with 50.
For Example :
<div class="intrinsic-container">
<iframe src="//www.youtube.com/embed/KMYrIi_Mt8A" allowfullscreen></iframe>
</div>
CSS
.intrinsic-container {
position: relative;
height: 0;
overflow: hidden;
}
/* 16x9 Aspect Ratio */
.intrinsic-container-16x9 {
padding-bottom: 56.25%;
}
/* 4x3 Aspect Ratio */
.intrinsic-container-4x3 {
padding-bottom: 75%;
}
.intrinsic-container iframe {
position: absolute;
top:0;
left: 0;
width: 100%;
height: 100%;
}
UPDATE
Just a quick note, as I can see this looks really stupid, and it has no good use with pure PHP because the array_merge
just works there. BUT try it with the PHP MongoDB driver before you rush to downvote. That dude WILL add indexes for whatever reason, and WILL ruin the merged object. With my naïve little function, the merge comes out exactly the way it was supposed to with a traditional array_merge
.
I know it's an old question but I'd like to add one more case I had recently with MongoDB driver queries and none of array_merge
, array_replace
nor array_push
worked. I had a bit complex structure of objects wrapped as arrays in array:
$a = [
["a" => [1, "a2"]],
["b" => ["b1", 2]]
];
$t = [
["c" => ["c1", "c2"]],
["b" => ["b1", 2]]
];
And I needed to merge them keeping the same structure like this:
$merged = [
["a" => [1, "a2"]],
["b" => ["b1", 2]],
["c" => ["c1", "c2"]],
["b" => ["b1", 2]]
];
The best solution I came up with was this:
public static function glueArrays($arr1, $arr2) {
// merges TWO (2) arrays without adding indexing.
$myArr = $arr1;
foreach ($arr2 as $arrayItem) {
$myArr[] = $arrayItem;
}
return $myArr;
}
from joblib import Parallel, delayed
import multiprocessing
inputs = range(10)
def processInput(i):
return i * i
num_cores = multiprocessing.cpu_count()
results = Parallel(n_jobs=num_cores)(delayed(processInput)(i) for i in inputs)
print(results)
The above works beautifully on my machine (Ubuntu, package joblib was pre-installed, but can be installed via pip install joblib
).
Taken from https://blog.dominodatalab.com/simple-parallelization/
Sorted array Swift 4.2
arrayOfRaces = arrayOfItems.sorted(by: { ($0["raceName"] as! String) < ($1["raceName"] as! String) })
My images are kept in a "hidden" folder above "www" so that only logged users are allowed access to them. For this reason I cannot use the ordinary <img src=/somefolder/1023.jpg>
but I send requests to the server like <img src=?1023>
and it responds by sending back the image kept under name '1023'.
The application is used for image cropping, so after an ajax request to crop the image, it is changed as content on the server but keeps its original name. In order to see the result of the cropping, after the ajax request has been completed, the first image is removed from the DOM and a new image is inserted with the same name <img src=?1023>
.
To avoid cashing I add to the request the "time" tag prepended with "#" so it becomes like <img src=?1023#1467294764124>
. The server automatically filters out the hash part of the request and responds correctly by sending back my image kept as '1023'. Thus I always get the last version of the image without much server-side decoding.
http://www.jquerybyexample.net/2012/05/open-link-in-new-tab-or-new-popup.html
$(document).ready(function() {
$('A.BLAH').click(function() {
var NWin = window.open($(this).prop('href'), '', 'height=600,width=1000');
if (window.focus)
{
NWin.focus();
}
return false;
});
});
replace p.setval(0);
with the following.
const unsigned int param = 0;
p.setval(param);
That way it knows for sure which type the constant 0 is.
conda
insteadNone of the proposed solutions worked for me on Raspbian 10 (buster)
so I just installed it via conda
and voila:
conda install -c anaconda cryptography
P.S. : I know that the question mentions pip
but I see that OP is using a conda
installation so I thought of sharing this solution anyway. Nevertheless, since this problem is apparently OS-specific, it's meaningful to remind one that conda
is a cross-platform and language-agnostic solution which may also install necessary binaries apart from python
packages - with just an one-liner.
When ever the array is declared, then only we have to add the key-value's in NSDictionary like
NSDictionary *normalDict = [[NSDictionary alloc]initWithObjectsAndKeys:@"Value1",@"Key1",@"Value2",@"Key2",@"Value3",@"Key3",nil];
we cannot add or remove the key values in this NSDictionary
Where as in NSMutableDictionary we can add the objects after intialization of array also by using this method
NSMutableDictionary *mutableDict = [[NSMutableDictionary alloc]init];'
[mutableDict setObject:@"Value1" forKey:@"Key1"];
[mutableDict setObject:@"Value2" forKey:@"Key2"];
[mutableDict setObject:@"Value3" forKey:@"Key3"];
for removing the key value we have to use the following code
[mutableDict removeObject:@"Value1" forKey:@"Key1"];
Since it has been a couple years and it doesn't seem possible to do this (using npm alone), a solution to this problem is to use the Nexus Repository Manager (from Sonatype). Nexus supports multiple repositories, lets you order them, and also proxies/caches to improve speed.
A free version and pro/paid version exist. The feature that supports this is described at: https://help.sonatype.com/repomanager3/node-packaged-modules-and-npm-registries
The relevant information is duplicated below so if/when the above URL/link stops working the information is still here.
A repository group is the recommended way to expose all your npm registries repositories from the repository manager to your users, without needing any further client side configuration. A repository group allows you to expose the aggregated content of multiple proxy and hosted repositories with one URL to npm and other tools.
It lets you create private npm registries
A private npm registry can be used to upload your own packages as well as third-party packages.
And
To reduce duplicate downloads and improve download speeds for your developers and CI servers, you should proxy the registry hosted at https://registry.npmjs.org. By default npm accesses this registry directly. You can also proxy any other registries you require.
So a quick bulleted list of things you do to get this working is:
Install Nexus
Create a local/private repo (or point to your private repo on another server)
Create a GROUP that lists your private repo, and the public repo.
Configure your $HOME/.npmrc file to point to the "GROUP" just created.
Publish your private npm packages to the local repo.
Users now can run a one time setup.
npm config set registry https://nexus/content/groups/GROUP
npm install
.
npm install my-private-package
npm install lodash any-other-public-package
And both your public and private packages can be installed via a simple npm install
command. Nexus finds the package searching each repo configured in the group and returns the results. So npm still thinks there is just one registry but behind the curtain there are multiple repos being used.
IMPORTANT NOTE: When you publish your components, you'll need to specify the npm publish --registry https://nexus/content/repositories/private-repo my-private-package
command so your package is published to the correct repo.
Update
And there's your problem - you do have to click event handlers for some a
elements. In this case, the order in which you attach the handlers matters since they'll be fired in that order.
Here's a working fiddle that shows the behaviour you want.
This should be your code:
$(document).ready(function(){
$('#tabs div.tab').hide();
$('#tabs div.tab:first').show();
$('#tabs ul li:first').addClass('active');
$("div.subtab_left li.notebook a").click(function(e) {
e.stopImmediatePropagation();
alert("asdasdad");
return false;
});
$('#tabs ul li a').click(function(){
alert("Handling link click");
$('#tabs ul li').removeClass('active');
$(this).parent().addClass('active');
var currentTab = $(this).attr('href');
$('#tabs div.tab').hide();
$(currentTab).show();
return false;
});
});
Note that the order of attaching the handlers has been exchanged and e.stopImmediatePropagation()
is used to stop the other click handler from firing while return false
is used to stop the default behaviour of following the link (as well as stopping the bubbling of the event. You may find that you need to use only e.stopPropagation
).
Play around with this, if you remove the e.stopImmediatePropagation()
you'll find that the second click handler's alert will fire after the first alert. Removing the return false
will have no effect on this behaviour but will cause links to be followed by the browser.
Note
A better fix might be to ensure that the selectors return completely different sets of elements so there is no overlap but this might not always be possible in which case the solution described above might be one way to consider.
I don't see why your first code snippet would not work. What's the default action that you're seeing that you want to stop?
If you've attached other event handlers to the link, you should look into event.stopPropagation()
and event.stopImmediatePropagation()
instead. Note that return false
is equivalent to calling both event.preventDefault
and event.stopPropagation()
ref
In your second code snippet, e
is not defined. So an error would thrown at e.preventDefault()
and the next lines never execute.
In other words
$("div.subtab_left li.notebook a").click(function() {
e.preventDefault();
alert("asdasdad");
return false;
});
should be
//note the e declared in the function parameters now
$("div.subtab_left li.notebook a").click(function(e) {
e.preventDefault();
alert("asdasdad");
return false;
});
Here's a working example showing that this code indeed does work and that return false
is not really required if you only want to stop the following of a link.
Hey define color #000
into as like you and modify your css as like this
.navBtn { text-decoration: none; color:#000; }
.navBtn:visited { text-decoration: none; color:#000; }
.navBtn:hover { text-decoration: none; color:#000; }
.navBtn:focus { text-decoration: none; color:#000; }
.navBtn:hover, .navBtn:active { text-decoration: none; color:#000; }
or this
li a { text-decoration: none; color:#000; }
li a:visited { text-decoration: none; color:#000; }
li a:hover { text-decoration: none; color:#000; }
li a:focus { text-decoration: none; color:#000; }
li a:hover, .navBtn:active { text-decoration: none; color:#000; }
An issue that DO arise in practical Android code is that comparing them with CharSequence.equals is valid but does not necessarily work as intended.
EditText t = (EditText )getView(R.id.myEditText); // Contains "OK"
Boolean isFalse = t.getText().equals("OK"); // will always return false.
Comparison should be made by
("OK").contentEquals(t.GetText());
Nearly everyone gives how directly, let me show the evolvement:
you can use the instance methods of Array:
// general form of closure
images.sortInPlace({ (image1: imageFile, image2: imageFile) -> Bool in return image1.fileID > image2.fileID })
// types of closure's parameters and return value can be inferred by Swift, so they are omitted along with the return arrow (->)
images.sortInPlace({ image1, image2 in return image1.fileID > image2.fileID })
// Single-expression closures can implicitly return the result of their single expression by omitting the "return" keyword
images.sortInPlace({ image1, image2 in image1.fileID > image2.fileID })
// closure's argument list along with "in" keyword can be omitted, $0, $1, $2, and so on are used to refer the closure's first, second, third arguments and so on
images.sortInPlace({ $0.fileID > $1.fileID })
// the simplification of the closure is the same
images = images.sort({ (image1: imageFile, image2: imageFile) -> Bool in return image1.fileID > image2.fileID })
images = images.sort({ image1, image2 in return image1.fileID > image2.fileID })
images = images.sort({ image1, image2 in image1.fileID > image2.fileID })
images = images.sort({ $0.fileID > $1.fileID })
For elaborate explanation about the working principle of sort, see The Sorted Function.
Adding to @Paco Zarate's terrific answer above, if you want to transpose a table which has multiple types of columns, then add this to the end of line 39, so it only transposes int
columns:
and C.system_type_id = 56 --56 = type int
Here is the full query that is being changed:
select @colsUnpivot = stuff((select ','+quotename(C.name)
from sys.columns as C
where C.object_id = object_id(@tableToPivot) and
C.name <> @columnToPivot and C.system_type_id = 56 --56 = type int
for xml path('')), 1, 1, '')
To find other system_type_id
's, run this:
select name, system_type_id from sys.types order by name
From the documentation:
We can add to a list in many ways:
assert [1,2] + 3 + [4,5] + 6 == [1, 2, 3, 4, 5, 6]
assert [1,2].plus(3).plus([4,5]).plus(6) == [1, 2, 3, 4, 5, 6]
//equivalent method for +
def a= [1,2,3]; a += 4; a += [5,6]; assert a == [1,2,3,4,5,6]
assert [1, *[222, 333], 456] == [1, 222, 333, 456]
assert [ *[1,2,3] ] == [1,2,3]
assert [ 1, [2,3,[4,5],6], 7, [8,9] ].flatten() == [1, 2, 3, 4, 5, 6, 7, 8, 9]
def list= [1,2]
list.add(3) //alternative method name
list.addAll([5,4]) //alternative method name
assert list == [1,2,3,5,4]
list= [1,2]
list.add(1,3) //add 3 just before index 1
assert list == [1,3,2]
list.addAll(2,[5,4]) //add [5,4] just before index 2
assert list == [1,3,5,4,2]
list = ['a', 'b', 'z', 'e', 'u', 'v', 'g']
list[8] = 'x'
assert list == ['a', 'b', 'z', 'e', 'u', 'v', 'g', null, 'x']
You can also do:
def myNewList = myList << "fifth"
You can use the 'netstat' command for this. There's a description of doing this sort of thing here.
The simplest way in Excel 2010: Select the column with the URL text, then select Hyperlink Style from the Home tab. All URLs in the column are now hyperlinks.
Also double clicking each cell at the end of the URL text and adding a blank or just enter will also produce a hyperlink. Similar to the way you have to create URL links in MS Outlook emails.
You create and use byte array I/O streams as follows:
byte[] source = ...;
ByteArrayInputStream bis = new ByteArrayInputStream(source);
// read bytes from bis ...
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// write bytes to bos ...
byte[] sink = bos.toByteArray();
Assuming that you are using a JDBC driver that implements the standard JDBC Blob interface (not all do), you can also connect a InputStream
or OutputStream
to a blob using the getBinaryStream
and setBinaryStream
methods1, and you can also get and set the bytes directly.
(In general, you should take appropriate steps to handle any exceptions, and close streams. However, closing bis
and bos
in the example above is unnecessary, since they aren't associated with any external resources; e.g. file descriptors, sockets, database connections.)
1 - The setBinaryStream
method is really a getter. Go figure.
Your stored procedures work as coded. The problem is with the last line, it is unable to invoke either of your stored procedures.
Three choices in SQL*Plus are: call
, exec
, and an anoymous PL/SQL block.
call
appears to be a SQL keyword, and is documented in the SQL Reference. http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_4008.htm#BABDEHHG The syntax diagram indicates that parentesis are required, even when no arguments are passed to the call routine.
CALL test_sp_1();
An anonymous PL/SQL block is PL/SQL that is not inside a named procedure, function, trigger, etc. It can be used to call your procedure.
BEGIN
test_sp_1;
END;
/
Exec
is a SQL*Plus command that is a shortcut for the above anonymous block. EXEC <procedure_name>
will be passed to the DB server as BEGIN <procedure_name>; END;
Full example:
SQL> SET SERVEROUTPUT ON
SQL> CREATE OR REPLACE PROCEDURE test_sp
2 AS
3 BEGIN
4 DBMS_OUTPUT.PUT_LINE('Test works');
5 END;
6 /
Procedure created.
SQL> CREATE OR REPLACE PROCEDURE test_sp_1
2 AS
3 BEGIN
4 DBMS_OUTPUT.PUT_LINE('Testing');
5 test_sp;
6 END;
7 /
Procedure created.
SQL> CALL test_sp_1();
Testing
Test works
Call completed.
SQL> exec test_sp_1
Testing
Test works
PL/SQL procedure successfully completed.
SQL> begin
2 test_sp_1;
3 end;
4 /
Testing
Test works
PL/SQL procedure successfully completed.
SQL>
I also found that when I uninstalled nunit v3.2.1, the nunit framework reference for v3.2.1 was still in my project in solution explorer. Solution Explorer > ProjectName > References
If you right click it will show the version. Remove this Then Right click on References > Add Reference.
Search for the version 2.x version and add then rebuild solution.
That worked for me!
You can try like:
var path="~/Image/test.png"; System.Web.Hosting.HostingEnvironment.MapPath( @ + path)
try
sudo chown mysql:mysql -R /var/lib/mysql
then start your mysql service
systemctl start mysqld
Another way to suppress the error: Add this line at the top in C/C++ file:
#define _CRT_SECURE_NO_WARNINGS
I suggest to not only store a boolean flag, but the complete version code. This way you can also query at the beginning if it is the first start in a new version. You can use this information to display a "Whats new" dialog, for example.
The following code should work from any android class that "is a context" (activities, services, ...). If you prefer to have it in a separate (POJO) class, you could consider using a "static context", as described here for example.
/**
* Distinguishes different kinds of app starts: <li>
* <ul>
* First start ever ({@link #FIRST_TIME})
* </ul>
* <ul>
* First start in this version ({@link #FIRST_TIME_VERSION})
* </ul>
* <ul>
* Normal app start ({@link #NORMAL})
* </ul>
*
* @author schnatterer
*
*/
public enum AppStart {
FIRST_TIME, FIRST_TIME_VERSION, NORMAL;
}
/**
* The app version code (not the version name!) that was used on the last
* start of the app.
*/
private static final String LAST_APP_VERSION = "last_app_version";
/**
* Finds out started for the first time (ever or in the current version).<br/>
* <br/>
* Note: This method is <b>not idempotent</b> only the first call will
* determine the proper result. Any subsequent calls will only return
* {@link AppStart#NORMAL} until the app is started again. So you might want
* to consider caching the result!
*
* @return the type of app start
*/
public AppStart checkAppStart() {
PackageInfo pInfo;
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
AppStart appStart = AppStart.NORMAL;
try {
pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
int lastVersionCode = sharedPreferences
.getInt(LAST_APP_VERSION, -1);
int currentVersionCode = pInfo.versionCode;
appStart = checkAppStart(currentVersionCode, lastVersionCode);
// Update version in preferences
sharedPreferences.edit()
.putInt(LAST_APP_VERSION, currentVersionCode).commit();
} catch (NameNotFoundException e) {
Log.w(Constants.LOG,
"Unable to determine current app version from pacakge manager. Defenisvely assuming normal app start.");
}
return appStart;
}
public AppStart checkAppStart(int currentVersionCode, int lastVersionCode) {
if (lastVersionCode == -1) {
return AppStart.FIRST_TIME;
} else if (lastVersionCode < currentVersionCode) {
return AppStart.FIRST_TIME_VERSION;
} else if (lastVersionCode > currentVersionCode) {
Log.w(Constants.LOG, "Current version code (" + currentVersionCode
+ ") is less then the one recognized on last startup ("
+ lastVersionCode
+ "). Defenisvely assuming normal app start.");
return AppStart.NORMAL;
} else {
return AppStart.NORMAL;
}
}
It could be used from an activity like this:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
switch (checkAppStart()) {
case NORMAL:
// We don't want to get on the user's nerves
break;
case FIRST_TIME_VERSION:
// TODO show what's new
break;
case FIRST_TIME:
// TODO show a tutorial
break;
default:
break;
}
// ...
}
// ...
}
The basic logic can be verified using this JUnit test:
public void testCheckAppStart() {
// First start
int oldVersion = -1;
int newVersion = 1;
assertEquals("Unexpected result", AppStart.FIRST_TIME,
service.checkAppStart(newVersion, oldVersion));
// First start this version
oldVersion = 1;
newVersion = 2;
assertEquals("Unexpected result", AppStart.FIRST_TIME_VERSION,
service.checkAppStart(newVersion, oldVersion));
// Normal start
oldVersion = 2;
newVersion = 2;
assertEquals("Unexpected result", AppStart.NORMAL,
service.checkAppStart(newVersion, oldVersion));
}
With a bit more effort you could probably test the android related stuff (PackageManager and SharedPreferences) as well. Anyone interested in writing the test? :)
Note that the above code will only work properly if you don't mess around with your android:versionCode
in AndroidManifest.xml!
If not handling a callback from the editing activity (with onActivityResult), then I'd rather put the logic you mentioned in onStart (or possibly in onRestart), since having it in onResume just seems like overkill, given that changes are only occurring after onStop.
At any rate, be familiar with the Activity lifecycle. Plus, take note of the onRestoreInstanceState and onSaveInstanceState methods, which do not appear in the pretty lifecycle diagram.
(Also, it's worth reviewing how the Notepad Tutorial handles what you're doing, though it does use a database.)
For IE browser:
<!--[if IE]>
<meta http-equiv="Content-Type" content="text/html; charset=Unicode">
<![endif]-->
For all non-IE browsers:
<![if !IE]>
<meta http-equiv="Content-Type" content="text/html; charset=utf8">
<![endif]>
For all IE greater than 8 OR all non-IE browsers :
<!--[if (gt IE 8)|!(IE)]><!--><script src="/_JS/library/jquery-2.1.1.min.js"></script><!--<![endif]-->
Use the wildcard "#" but beware that at some point you will have to somehow understand the data passing through the bus!
You can use CSS hover in combination with an image background.
CSS
.image
{
background:url(images/back.png);
height:100px;
width:100px;
display: block;
float:left;
}
.image a {
display: none;
}
.image a:hover {
display: block;
}
HTML
<div class="image"><a href="#">Text you want on mouseover</a></div>
I had the same problem, but its an easy fix! Just set
status bar is initially hidden = YES
then add an row by clicking on the plus right after the text status bar is initially hidden
, then set the text to
view controller-based status bar appearance
by clicking the arrows, and set it to NO
Hope this helps!
Recently, I really enjoy shorthand if else statements as a swtich case replacement. In my opinion, this is better in read and take less place. Just take a look:
var redirectUrl =
status == LoginStatusEnum.Success ? "/SecretPage"
: status == LoginStatusEnum.Failure ? "/LoginFailed"
: status == LoginStatusEnum.Sms ? "/2-StepSms"
: status == LoginStatusEnum.EmailNotConfirmed ? "/EmailNotConfirmed"
: "/404-Error";
instead of
string redirectUrl;
switch (status)
{
case LoginStatusEnum.Success:
redirectUrl = "/SecretPage";
break;
case LoginStatusEnum.Failure:
redirectUrl = "/LoginFailed";
break;
case LoginStatusEnum.Sms:
redirectUrl = "/2-StepSms";
break;
case LoginStatusEnum.EmailNotConfirmed:
redirectUrl = "/EmailNotConfirmed";
break;
default:
redirectUrl = "/404-Error";
break;
}
Vertical alignment is now very simple by the use of Flexible box layout. Nowadays, this method is supported in a wide range of web browsers except Internet Explorer 8 & 9. Therefore we'd need to use some hacks/polyfills or different approaches for IE8/9.
In the following I'll show you how to do that in only 3 lines of text (regardless of old flexbox syntax).
Note: it's better to use an additional class instead of altering .jumbotron
to achieve the vertical alignment. I'd use vertical-center
class name for instance.
Example Here (A Mirror on jsbin).
<div class="jumbotron vertical-center"> <!--
^--- Added class -->
<div class="container">
...
</div>
</div>
.vertical-center {
min-height: 100%; /* Fallback for browsers do NOT support vh unit */
min-height: 100vh; /* These two lines are counted as one :-) */
display: flex;
align-items: center;
}
Important notes (Considered in the demo):
A percentage values of height
or min-height
properties is relative to the height
of the parent element, therefore you should specify the height
of the parent explicitly.
Vendor prefixed / old flexbox syntax omitted in the posted snippet due to brevity, but exist in the online example.
In some of old web browsers such as Firefox 9 (in which I've tested), the flex container - .vertical-center
in this case - won't take the available space inside the parent, therefore we need to specify the width
property like: width: 100%
.
Also in some of web browsers as mentioned above, the flex item - .container
in this case - may not appear at the center horizontally. It seems the applied left/right margin
of auto
doesn't have any effect on the flex item.
Therefore we need to align it by box-pack / justify-content
.
For further details and/or vertical alignment of columns, you could refer to the topic below:
This is the old answer I wrote at the time I answered this question. This method has been discussed here and it's supposed to work in Internet Explorer 8 and 9 as well. I'll explain it in short:
In inline flow, an inline level element can be aligned vertically to the middle by vertical-align: middle
declaration. Spec from W3C:
middle
Align the vertical midpoint of the box with the baseline of the parent box plus half the x-height of the parent.
In cases that the parent - .vertical-center
element in this case - has an explicit height
, by any chance if we could have a child element having the exact same height
of the parent, we would be able to move the baseline of the parent to the midpoint of the full-height child and surprisingly make our desired in-flow child - the .container
- aligned to the center vertically.
That being said, we could create a full-height element within the .vertical-center
by ::before
or ::after
pseudo elements and also change the default display
type of it and the other child, the .container
to inline-block
.
Then use vertical-align: middle;
to align the inline elements vertically.
Here you go:
<div class="jumbotron vertical-center">
<div class="container">
...
</div>
</div>
.vertical-center {
height:100%;
width:100%;
text-align: center; /* align the inline(-block) elements horizontally */
font: 0/0 a; /* remove the gap between inline(-block) elements */
}
.vertical-center:before { /* create a full-height inline block pseudo=element */
content: " ";
display: inline-block;
vertical-align: middle; /* vertical alignment of the inline element */
height: 100%;
}
.vertical-center > .container {
max-width: 100%;
display: inline-block;
vertical-align: middle; /* vertical alignment of the inline element */
/* reset the font property */
font: 16px/1 "Helvetica Neue", Helvetica, Arial, sans-serif;
}
Also, to prevent unexpected issues in extra small screens, you can reset the height of the pseudo-element to auto
or 0
or change its display
type to none
if needed so:
@media (max-width: 768px) {
.vertical-center:before {
height: auto;
/* Or */
display: none;
}
}
And one more thing:
If there are footer
/header
sections around the container, it's better to position that elements properly (relative
, absolute
? up to you.) and add a higher z-index
value (for assurance) to keep them always on the top of the others.