According to oracle online documentation
ORA-12541: TNS:no listener
Cause: The connection request could not be completed because the listener is not running.
Action: Ensure that the supplied destination address matches one of the addresses used by
the listener - compare the TNSNAMES.ORA entry with the appropriate LISTENER.ORA file (or
TNSNAV.ORA if the connection is to go by way of an Interchange). Start the listener on
the remote machine.
Try replacing apt-get
with yum
as Amazon Linux based AMI uses the yum
command instead of apt-get
.
I tried with many solutions but it didn't work for me so I tried flex with the table and it worked fine for me with all table functionalities like border-collapse and so on only change is display property
This was my HTML requirement
<table>
<thead>
<tr>
<th>1</th>
<th colspan="3">2</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td colspan="3">2</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td colspan="2">3</td>
</tr>
</tbody>
</table>
My CSS
table{
display: flex;
flex-direction: column;
}
table tr{
display: flex;
width: 100%;
}
table > thead > tr > th:first-child{
width: 20%;
}
table > thead > tr > th:last-child{
width: 80%;
}
table > tbody tr > td:first-child{
width: 10%;
}
table > tbody tr > td{
width: 30%;
}
table > tbody tr > td[colspan="2"]{
width: 60%;
}
table > tbody tr > td[colspan="3"]{
width: 90%;
}
/*This is to remove border making 1px space on right*/
table > tbody tr > td:last-child{
border-right: 0;
}
The article Semicolons in JavaScript are optional makes some really good points about not using semi colons in Javascript. It deals with all the points have been brought up by the answers to this question.
Use position:fixed
on the video, set it to 100% width/height, and put a negative z-index
on it so it appears behind everything.
If you look at VideoJS, the controls are just html elements sitting on top of the video, using z-index to make sure they're above.
HTML
<video id="video_background" src="video.mp4" autoplay>
(Add webm and ogg sources to support more browsers)
CSS
#video_background {
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
z-index: -1000;
}
It'll work in most HTML5 browsers, but probably not iPhone/iPad, where the video needs to be activated, and doesn't like elements over it.
One important thing... if you have something like:
body {
zoom: 0.9;
}
You need make the equivilent thing in canvas:
canvas {
zoom: 1.1;
}
declaring the list (and initializing it with an empty arraylist)
List<Card> cardList = new ArrayList<Card>();
adding an element:
Card card;
cardList.add(card);
iterating over elements:
for(Card card : cardList){
System.out.println(card);
}
My requirements were a bit different than the ones asked on the original question, but hopefully I might help someone who is going through the same problem that I was..
I had to define if a field was required or not based on a scope variable.. So I basically had to set ng-required="myScopeVariable"
(which is a boolean variable).
<div class="align-left" ng-repeat="schema in schemas">
<input type="text" ng-required="schema.Required" />
</div>
I am using Eclipse. I have resolved this problem by the following:
You will not get any this kind of error.
Try the JavaScriptSerializer instead of the DataContractJsonSerializer
JavaScriptSerializer serializer = new JavaScriptSerializer();
var output = serializer.Serialize(your_anon_object);
You just need to put the file path (directory) before the name of the image. Example:
fig.savefig('/home/user/Documents/graph.png')
Other example:
fig.savefig('/home/user/Downloads/MyImage.png')
This code works very well
function isUndefined(array, index) {
return ((String(array[index]) == "undefined") ? "Yes" : "No");
}
I have tried almost all the answers and some of them almost worked for me but none of these answers work perfectly. So here is my solution. For this solution, you will need to add onclick
attribute in the HTML body tag. So if you can not modify the HTML file then this solution won't work for you.
Step 1: add onclick
attribute in the HTML body tag like this:
<body onclick="ok.performClick(this.value);">
<h1>This is heading 1</h1>
<p>This is para 1</p>
</body>
Step 2: implement addJavascriptInterface
in your app to handle click listener:
webView.addJavascriptInterface(new Object() {
@JavascriptInterface
public void performClick(String string) {
handler.sendEmptyMessageDelayed(CLICK_ON_WEBVIEW, 0);
}
}, "ok");
Step 3: We can not perform any action on main thread from performClick
method so need to add Handler
class:
private final Handler handler = new Handler(this); // class-level variable
private static final int CLICK_ON_WEBVIEW = 1; // class-level variable
implement Handler.Callback
to your class and the override handleMessage
@Override
public boolean handleMessage(Message message) {
if (message.what == CLICK_ON_WEBVIEW) {
Toast.makeText(getActivity(), "WebView clicked", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
You can get free Virtual Machine and many more things online for 3 months provided by Microsoft Azure. I guess you need VPN for learning purpose. For that it would suffice.
Check your problem is solved.
In computer programming, particularly in the C, C++, and C# programming languages, a variable or object declared with the volatile
keyword usually has special properties related to optimization and/or threading. Generally speaking, the volatile
keyword is intended to prevent the (pseudo)compiler from applying any optimizations on the code that assume values of variables cannot change "on their own." (c) Wikipedia
For print session data you do not need to use print_r() function every time .
If you use it then it will be non-readable format.Data will be looks very dirty.
But if you use my function all you have to do is to use p()-Funtion and pass data into it. //create new file into application/cms_helper.php and load helper cms into //autoload or on controller
/*Copy Code for p function from here and paste into cms_helper.php in application/helpers folder */
//@parram $data-array,$d-if true then die by default it is false
//@author Your name
function p($data,$d = false){
echo "<pre>";
print_r($data);
echo "</pre>";
if($d == TRUE){
die();
}
}
Just remember to load cms_helper into your project or controller using $this->load->helper('cms'); use bellow code into your controller or model it will works just GREAT.
p($this->session->all_userdata()); // it will apply pre to your sesison data and other array as well
The version 49.0.2623.75 (64-bit) is not in beta anymore.
The command to fix the CORS issue is
google-chrome-stable --disable-web-security --user-data-dir
Use those queries to find all FKs:
Declare @SchemaName VarChar(200) = 'Schema Name'
Declare @TableName VarChar(200) = 'Table name'
-- Find FK in This table.
SELECT
'IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
+ ''') AND parent_object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].['
+ OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +
'ALTER TABLE ' + OBJECT_SCHEMA_NAME(FK.parent_object_id) +
'.[' + OBJECT_NAME(FK.parent_object_id) +
'] DROP CONSTRAINT ' + FK.name
, S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O
ON (O.object_id = FK.parent_object_id )
INNER JOIN SYS.schemas AS S
ON (O.schema_id = S.schema_id)
WHERE
O.name = @TableName
And S.name = @SchemaName
-- Find the FKs in the tables in which this table is used
SELECT
' IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
+ ''') AND parent_object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].['
+ OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +
' ALTER TABLE ' + OBJECT_SCHEMA_NAME(FK.parent_object_id) +
'.[' + OBJECT_NAME(FK.parent_object_id) +
'] DROP CONSTRAINT ' + FK.name
, S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O
ON (O.object_id = FK.referenced_object_id )
INNER JOIN SYS.schemas AS S
ON (O.schema_id = S.schema_id)
WHERE
O.name = @TableName
And S.name = @SchemaName
Because you have to set the line-height
to the height of the div for this to work
I used AndExplorer for this purpose and my solution is popup a dialog and then redirect on the market to install the misssing application:
My startCreation is trying to call external file/directory picker. If it is missing call show installResultMessage function.
private void startCreation(){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
Uri startDir = Uri.fromFile(new File("/sdcard"));
intent.setDataAndType(startDir,
"vnd.android.cursor.dir/lysesoft.andexplorer.file");
intent.putExtra("browser_filter_extension_whitelist", "*.csv");
intent.putExtra("explorer_title", getText(R.string.andex_file_selection_title));
intent.putExtra("browser_title_background_color",
getText(R.string.browser_title_background_color));
intent.putExtra("browser_title_foreground_color",
getText(R.string.browser_title_foreground_color));
intent.putExtra("browser_list_background_color",
getText(R.string.browser_list_background_color));
intent.putExtra("browser_list_fontscale", "120%");
intent.putExtra("browser_list_layout", "2");
try{
ApplicationInfo info = getPackageManager()
.getApplicationInfo("lysesoft.andexplorer", 0 );
startActivityForResult(intent, PICK_REQUEST_CODE);
} catch( PackageManager.NameNotFoundException e ){
showInstallResultMessage(R.string.error_install_andexplorer);
} catch (Exception e) {
Log.w(TAG, e.getMessage());
}
}
This methos is just pick up a dialog and if user wants install the external application from market
private void showInstallResultMessage(int msg_id) {
AlertDialog dialog = new AlertDialog.Builder(this).create();
dialog.setMessage(getText(msg_id));
dialog.setButton(getText(R.string.button_ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
dialog.setButton2(getText(R.string.button_install),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=lysesoft.andexplorer"));
startActivity(intent);
finish();
}
});
dialog.show();
}
Try to change Long
object type to long
primitive type (if using primitives is ok for you).
I had the same problem and changing type helped me.
Using awk.
i starts at 0, i++
will increment the value of i, but return the original value that i held before being incremented.
awk '{print i++ "," $0}' file
.yourWrapperClass * {
/* your styles for ALL */
}
This code will apply styles all elements inside .yourWrapperClass.
var str = document.getElementById('mydiv').innerHTML;
document.getElementById('mytextarea').innerHTML = str.replace(/<br\s*[\/]?>/gi, "\n");
or using jQuery:
var str = $("#mydiv").html();
var regex = /<br\s*[\/]?>/gi;
$("#mydiv").html(str.replace(regex, "\n"));
edit: added i
flag
edit2: you can use /<br[^>]*>/gi
which will match anything between the br
and slash
if you have for example <br class="clear" />
You're almost there. As you can see, the onItemSelected
will give you a position
parameter, you can use this to retrieve the object from your adapter, as in getItemAtPosition(position)
.
Example:
spinner.setOnItemSelectedListener(this);
...
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
This will put a message on screen, with the selected item printed by its toString() method.
First find the version you are using for GIT.
using this command : git --version
if you have a newer version than 1.7.10.
Then simply use this this command.
Windows:
git config --global credential.helper wincred
MAC
git config --global credential.helper osxkeychain
.NET DDD Sample from Domain-Driven Design Book by Eric Evans can be found here: http://dddsamplenet.codeplex.com
Cheers,
Jakub G
I'm using useEffect
hook to overcome the headache of doing all this so now I pass a variable down to child like this:
<ParentComponent>
<ChildComponent arbitrary={value} />
</ParentComponent>
useEffect(() => callTheFunctionToBeCalled(value) , [value]);
How about this? (jsFiddle link)
CSS
ul {
background: #CCC;
height: 1000%;
width: 100%;
list-style-position: outside;
margin: 0; padding: 0;
position: absolute;
}
li {
background-color: #EBEBEB;
border-bottom: 1px solid #CCCCCC;
border-right: 1px solid #CCCCCC;
display: table;
height: 180px;
overflow: hidden;
width: 200px;
}
.divone{
display: table-cell;
margin: 0 auto;
text-align: center;
vertical-align: middle;
width: 100%;
}
img {
width: 100%;
height: 410px;
}
.wrapper {
position: absolute;
}
If you're open to using jQuery:
<script type="text/javascript">
function fncsave()
{
$('#<%= savebtn.ClientID %>').click();
}
</script>
Also, if you are using .NET 4 or better you can make the ClientIDMode == static
and simplify the code:
<script type="text/javascript">
function fncsave()
{
$("#savebtn").click();
}
</script>
Reference: MSDN Article for Control.ClientIDMode
The problem is your gradle build is not finding the JAVA_HOME path or JDK folder. So, you could declare the path in gradle.properties like org.gradle.java.home=C:\Program Files\Java\[or yours jdk folder name].
Use this guide for using gradle.properties.
Or (and I prefer this solution) include JAVA_HOME path in systmem variables and restart CMD.
You can add header "Content-Type: text/html; charset=UTF-8" to your message body.
$headers = "Content-Type: text/html; charset=UTF-8";
If you use native mail()
function $headers array will be the 4th parameter
mail($to, $subject, $message, $headers)
If you user PEAR Mail::factory() code will be:
$smtp = Mail::factory('smtp', $params);
$mail = $smtp->send($to, $headers, $body);
You can use registry to set IE version for webbrowser control. Go to: HKLM\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION and add "yourApplicationName.exe" with value of browser_emulation To see value of browser_emulation, refer link: http://msdn.microsoft.com/en-us/library/ee330730%28VS.85%29.aspx#browser_emulation
If you using Bootstrap:
The current version of Bootstrap (3.0.2) (with jQuery 1.10.2 & Chrome) seems to generate this warning as well.
(It does so on Twitter too, BTW.)
The current version of Bootstrap (3.1.0) no longer seems to generate this warning.
That will be possible only if the HTML file is also loaded with the file
protocol from the local user's harddisk.
If the HTML page is served by HTTP from a server, you can't access any local files by specifying them in a src
attribute with the file://
protocol as that would mean you could access any file on the users computer without the user knowing which would be a huge security risk.
As Dimitar Bonev said, you can access a file if the user selects it using a file selector on their own. Without that step, it's forbidden by all browsers for good reasons. Thus, while his answer might prove useful for many people, it loosens the requirement from the code in the original question.
String s = "1";
try {
long l = Long.parseLong(s);
} catch (NumberFormatException e) {
System.out.println("NumberFormatException: " + e.getMessage());
}
I found a new error code which is not documented above: CFNetworkErrorCode -1022
Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection."
To list tags I prefer:
git tag -n
The -n
flag displays the first line of the annotation message along with the tag, or the first commit message line if the tag is not annotated.
You can also do git tag -n5
to show the first 5 lines of the annotation.
Use the following instead:
boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );
This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.
Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.
It's preferable to use context managers to close the files automatically
with open("new.txt", "r"), open('xyz.txt', 'w') as textfile, myfile:
for line in textfile:
var1, var2 = line.split(",");
myfile.writelines(var1)
It's possible to do it in CSS
.disabled{_x000D_
cursor:default;_x000D_
pointer-events:none;_x000D_
text-decoration:none;_x000D_
color:black;_x000D_
}
_x000D_
<a href="https://www.google.com" target="_blank" class="disabled">Google</a>
_x000D_
See at:
Please note that the text-decoration: none;
and color: black;
is not needed but it makes the link look more like plain text.
A slightly simpler syntax (in Robomongo at least) worked for me:
db.database.save({ Year : NumberInt(2015) });
First you need to define a LocationListener
to handle location changes.
private final LocationListener mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(final Location location) {
//your code here
}
};
Then get the LocationManager
and ask for location updates
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME,
LOCATION_REFRESH_DISTANCE, mLocationListener);
}
And finally make sure that you have added the permission on the Manifest,
For using only network based location use this one
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
For GPS based location, this one
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Surround what you want to be bold with:
<span style="font-weight:bold">Your bold text</span>
This would go inside your <td>
tag.
To solve this problem in Excel, usually I would just type in the literal row number of the cell above, e.g., if I'm typing in Cell A7
, I would use the formula =A6
. Then if I copied that formula to other cells, they would also use the row of the previous cell.
Another option is to use Indirect()
, which resolves the literal statement inside to be a formula. You could use something like:
=INDIRECT("A" & ROW() - 1)
The above formula will resolve to the value of the cell in column A
and the row that is one less than that of the cell which contains the formula.
I bought a theme from www.xamltemplates.net. The themes ship with source code so you can tweak them. They also offer a free theme (source code included).
Just a small remark:
some Safari browsers do not seem to respect neither the "hidden" attribute nor the style setting "display:none" (tested with Safari 12.1 under MacOS 10.12.6). Without an explicit placeholder text, these browsers simply show an empty first line in the list of options. It may therefore be useful to always provide some explanatory text for this "dummy" entry:
<option hidden disabled selected value>(select an option)</option>
Thanks to the "disabled" attribute, it won't be actively selected anyway.
$sUrl = 'http://www.linktopage.com/login/';
$params = array('http' => array(
'method' => 'POST',
'content' => 'username=admin195&password=d123456789'
));
$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if(!$fp) {
throw new Exception("Problem with $sUrl, $php_errormsg");
}
$response = @stream_get_contents($fp);
if($response === false) {
throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}
According to eduLINQ:
The best way to get to grips with what GroupJoin does is to think of Join. There, the overall idea was that we looked through the "outer" input sequence, found all the matching items from the "inner" sequence (based on a key projection on each sequence) and then yielded pairs of matching elements. GroupJoin is similar, except that instead of yielding pairs of elements, it yields a single result for each "outer" item based on that item and the sequence of matching "inner" items.
The only difference is in return statement:
Join:
var lookup = inner.ToLookup(innerKeySelector, comparer);
foreach (var outerElement in outer)
{
var key = outerKeySelector(outerElement);
foreach (var innerElement in lookup[key])
{
yield return resultSelector(outerElement, innerElement);
}
}
GroupJoin:
var lookup = inner.ToLookup(innerKeySelector, comparer);
foreach (var outerElement in outer)
{
var key = outerKeySelector(outerElement);
yield return resultSelector(outerElement, lookup[key]);
}
Read more here:
In My case, add the package Microsoft.EntityFrameworkCore.Tools fixed problem
I know this thread is a bit old but, I was looking for something similar and could not find it. Here's what I came up with. I create a string object using the .Net String class to expose all the methods normally found if using C#
[System.String]$myString
$myString = "237801_201011221155.xml"
$startPos = $myString.LastIndexOf("_") + 1 # Do not include the "_" character
$subString = $myString.Substring($startPos,$myString.Length - $startPos)
Result: 201011221155.xml
If escaping your single quote with another single quote isn't working for you (like it didn't for one of my recent REPLACE()
queries), you can use SET QUOTED_IDENTIFIER OFF
before your query, then SET QUOTED_IDENTIFIER ON
after your query.
For example
SET QUOTED_IDENTIFIER OFF;
UPDATE TABLE SET NAME = REPLACE(NAME, "'S", "S");
SET QUOTED_IDENTIFIER ON;
-- set OFF then ON again
On textarea resizing in webkit based browsers:
Setting max-height and max-width on the textarea will not remove the visual resize handle. Try:
resize: none;
(and yes I agree with "try to avoid doing anything which breaks the user's expectation", but sometimes it does make sense, i.e. in the context of a web application)
To customize the look and feel of webkit form elements from scratch:
-webkit-appearance: none;
You can go fullscreen automatically by putting this code in:
var elem = document.documentElement; if (elem.requestFullscreen) { elem.requestFullscreen() }
demo: https://codepen.io/ConfidentCoding/pen/ewLyPX
note: does not always work for security reasons. but it works for me at least. does not work when inspecting and pasting the code.
First I struggled a bit with a
DELETE FROM ... USING ... WHERE query,...
Since i wanted to test first
so i tried with SELECT FROM ... USING... WHERE ...
and this caused an error , ...
Then i wanted to reduce the number of deletions adding
LIMIT 10
which also produced an error
Then i removed the "LIMIT" and - hurray - it worked:
"1867 rows deleted. (Query took 1.3025 seconds.)"
The query was:
DELETE FROM tableX
USING tableX , tableX as Dup
WHERE NOT tableX .id = Dup.id
AND tableX .id > Dup.id
AND tableX .email= Dup.email
AND tableX .mobil = Dup.mobil
This worked.
If you're using iptables try:
iptables -nL
or
iptables -nL | grep 445
Want to center an image? Very easy, Bootstrap comes with two classes, .center-block
and text-center
.
Use the former in the case of your image being a BLOCK
element, for example, adding img-responsive
class to your img
makes the img
a block element. You should know this if you know how to navigate in the web console and see applied styles to an element.
Don't want to use a class? No problem, here is the CSS bootstrap uses. You can make a custom class or write a CSS rule for the element to match the Bootstrap class.
// In case you're dealing with a block element apply this to the element itself
.center-block {
margin-left:auto;
margin-right:auto;
display:block;
}
// In case you're dealing with a inline element apply this to the parent
.text-center {
text-align:center
}
You have mostly the right idea, it's just the sending of the form that is wrong. The form belongs in the body of the request.
req, err := http.NewRequest("POST", url, strings.NewReader(form.Encode()))
If you want to make a safe conversion and enjoy the use of Java8 with Lambda expression You can use it like:
val -> Optional.ofNullable(val).map(Long::intValue).orElse(null)
Also removing the submodule and then running git submodule init
and git submodule update
will obviously do the trick, but may not always be appropriate or possible.
I had the exactly same issue, with a very very long stack trace. At the end of the trace I saw this:
InvalidQueryException: Keyspace 'mykeyspace' does not exist
I created the keyspace in cassandra, and solved the problem.
CREATE KEYSPACE mykeyspace
WITH REPLICATION = {
'class' : 'SimpleStrategy',
'replication_factor' : 1
};
I was getting this error due to something even simpler (you could even say trivial). I hadn't installed the pytest
module. So a simple apt install python-pytest
fixed it for me.
'pytest' would have been listed in setup.py as a test dependency. Make sure you install the test requirements as well.
The notion of multi-module projects is there to service the needs of codependent segments of a project. Such a client depends on the services which in turn depends on say EJBs or data-access routines. You could group your continuous integration (CI) tests in this manner. I would rationalize that by saying that the CI tests need to be in lock-step with application logic changes.
Suppose your project is structured as:
project-root
|
+ --- ci
|
+ --- client
|
+ --- server
The project-root/pom.xml
defines modules
<modules>
<module>ci</module>
<module>client</module>
<module>server</module>
</modules>
The ci/pom.xml
defines profiles such as:
...
<profiles>
<profile>
<id>default</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</profile>
<profile>
<id>CI</id>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>false</skip>
</configuration>
</plugin>
</profile>
</profiles>
This will result in Maven skipping tests in this module except when the profile named CI
is active.
Your CI server must be instructed to execute mvn clean package -P CI
. The Maven web site has an in-depth explanation of the profiling mechanism.
This is alternative of brad anser - you can use comma as follows
onclick="funA(), funB(), ..."
however is better to NOT use this approach - for small projects you can use onclick only in case of one function calling (more: updated unobtrusive javascript).
function funA() {_x000D_
console.log('A');_x000D_
}_x000D_
_x000D_
function funB(clickedElement) {_x000D_
console.log('B: ' + clickedElement.innerText);_x000D_
}_x000D_
_x000D_
function funC(cilckEvent) {_x000D_
console.log('C: ' + cilckEvent.timeStamp);_x000D_
}
_x000D_
div {cursor:pointer}
_x000D_
<div onclick="funA(), funB(this), funC(event)">Click me</div>
_x000D_
Update 2018
Since the original answer HTML5 validation is now supported in all modern browsers. Now the easiest way to make a field required is simply using the required attibute.
<input type="email" class="form-control" id="exampleInputEmail1" required>
or in compliant HTML5:
<input type="email" class="form-control" id="exampleInputEmail1" required="true">
Read more on Bootstrap 4 validation
In Bootstrap 3, you can apply a "validation state" class to the parent element: http://getbootstrap.com/css/#forms-control-validation
For example has-error
will show a red border around the input. However, this will have no impact on the actual validation of the field. You'd need to add some additional client (javascript) or server logic to make the field required.
Demo: http://bootply.com/90564
add xrange=range
in your code :) It works to me.
For Java 8 ....
There is a good solution at https://stackoverflow.com/a/36315051/2648077 post.
This uses Java 8 Supplier
functional interface
I also had this problem the tableView wasn't the last view in the hierarchy. In my case i had a view above (even though they were not overlapping each other), so i dragged it above the tableView in the hierarchy and that made it.
Okay, so I've joined the google group of libphonenumber ( https://groups.google.com/forum/?hl=en&fromgroups#!forum/libphonenumber-discuss ) and I've asked a question.
I don't need to set the country in parameter if my phone number begins with "+". Here is an example :
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
// phone must begin with '+'
PhoneNumber numberProto = phoneUtil.parse(phone, "");
int countryCode = numberProto.getCountryCode();
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}
This is more readable and good practice too.
if(!status){
//do sth
}else{
//do sth
}
It was solved for me with the Laravel default public/.htaccess file adding an extra line:
The /public/.htaccess
file remains as follows:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
DirectoryIndex index.php # This line does the trick
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
You can connect one computer to another computer in a network by using these two methods:
Here is the example to connect using wmi module:
ip = '192.168.1.13'
username = 'username'
password = 'password'
from socket import *
try:
print("Establishing connection to %s" %ip)
connection = wmi.WMI(ip, user=username, password=password)
print("Connection established")
except wmi.x_wmi:
print("Your Username and Password of "+getfqdn(ip)+" are wrong.")
The second method is to use netuse module.
By Netuse, you can connect to remote computer. And you can access all data of the remote computer. It is possible in the following two ways:
Connect by virtual connection.
import win32api
import win32net
ip = '192.168.1.18'
username = 'ram'
password = 'ram@123'
use_dict={}
use_dict['remote']=unicode('\\\\192.168.1.18\C$')
use_dict['password']=unicode(password)
use_dict['username']=unicode(username)
win32net.NetUseAdd(None, 2, use_dict)
To disconnect:
import win32api
import win32net
win32net.NetUseDel('\\\\192.168.1.18',username,win32net.USE_FORCE)
Mount remote computer drive in local system.
import win32api
import win32net
import win32netcon,win32wnet
username='user'
password='psw'
try:
win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_DISK, 'Z:','\\\\192.168.1.18\\D$', None, username, password, 0)
print('connection established successfully')
except:
print('connection not established')
To unmount remote computer drive in local system:
import win32api
import win32net
import win32netcon,win32wnet
win32wnet.WNetCancelConnection2('\\\\192.168.1.4\\D$',1,1)
Before using netuse you should have pywin32 install in your system with python also.
Source: Connect remote system.
You can use the -quit
option of find
:
find <dir> -maxdepth 1 -type d -name '*foo*' -print -quit
Add this to your ~/.bashrc
, then logout and back in to take effect.
if [ ! -S ~/.ssh/ssh_auth_sock ]; then
eval `ssh-agent`
ln -sf "$SSH_AUTH_SOCK" ~/.ssh/ssh_auth_sock
fi
export SSH_AUTH_SOCK=~/.ssh/ssh_auth_sock
ssh-add -l > /dev/null || ssh-add
This should only prompt for a password the first time you login after each reboot. It will keep reusing the same ssh-agent
as long as it stays running.
(?<=\().*(?=\))
If you want to select text between two matching parentheses, you are out of luck with regular expressions. This is impossible(*).
This regex just returns the text between the first opening and the last closing parentheses in your string.
(*) Unless your regex engine has features like balancing groups or recursion. The number of engines that support such features is slowly growing, but they are still not a commonly available.
I dislike the chaining thens. The second then does not have access to status. As stated before 'response.json()' returns a promise. Returning the then result of 'response.json()' in a acts similar to a second then. It has the added bonus of being in scope of the response.
return fetch(url, params).then(response => {
return response.json().then(body => {
if (response.status === 200) {
return body
} else {
throw body
}
})
})
Select
cast(replace(convert(decimal(15,2),acs_daily_debit), '.', ',') as varchar(20))
from acs_balance_details
you can use ClearContents. ex,
Range("X").Cells.ClearContents
If it is a string
then use the built in float
on it to do the conversion for instance:
print( "%.5f" % float("1.43572e-03"))
answer:0.00143572
if You want to change opacity for all dialog then change in jquery-ui.css
/* Overlays */
.ui-widget-overlay
{
background: #5c5c5c url(images/ui-bg_flat_50_5c5c5c_40x100.png) 50% 50% repeat-x;
opacity: .50;
filter: Alpha(Opacity=80);
}
process.env.ENV_VARIABLE
Where ENV_VARIABLE
is the name of the variable you wish to access.
I vote for Karthik T's answer. you don't need to open a terminal to run commands.
For example,
// file: RunShellCommandFromJava.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class RunShellCommandFromJava {
public static void main(String[] args) {
String command = "ping -c 3 www.google.com";
Process proc = Runtime.getRuntime().exec(command);
// Read the output
BufferedReader reader =
new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}
proc.waitFor();
}
}
The output:
$ javac RunShellCommandFromJava.java
$ java RunShellCommandFromJava
PING http://google.com (123.125.81.12): 56 data bytes
64 bytes from 123.125.81.12: icmp_seq=0 ttl=59 time=108.771 ms
64 bytes from 123.125.81.12: icmp_seq=1 ttl=59 time=119.601 ms
64 bytes from 123.125.81.12: icmp_seq=2 ttl=59 time=11.004 ms
--- http://google.com ping statistics ---
3 packets transmitted, 3 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 11.004/79.792/119.601/48.841 ms
I'm not cool enough to be able to comment on a post. so I guess I need to make a new post. However the above recommendation of "sudo nmap -sn 192.168.0.0/24" is the best quickest method to get the all the MACs for the IPs on your local network/vlan/subnet What the OP doesnt mention, is the only way to get the MAC address this way, you MUST use sudo(or other super user privs i.e. windows admin) the command nmap -sn 192.168.0.0/24 will discover hosts on your network, however will not return the MACs as you are not in SU mode of operation.
Try nsiqcppstyle. It's a Python based coding style checker for C/C++. It's easy to extend to add your own rules.
Pyflakes does what you ask, it just checks the syntax. From the docs:
Pyflakes makes a simple promise: it will never complain about style, and it will try very, very hard to never emit false positives.
Pyflakes is also faster than Pylint or Pychecker. This is largely because Pyflakes only examines the syntax tree of each file individually.
To install and use:
$ pip install pyflakes
$ pyflakes yourPyFile.py
In the case of HashMap
, it replaces the old value with the new one.
In the case of HashSet
, the item isn't inserted.
The (very) short answer to your question is that paintComponent
is called "when it needs to be." Sometimes it's easier to think of the Java Swing GUI system as a "black-box," where much of the internals are handled without too much visibility.
There are a number of factors that determine when a component needs to be re-painted, ranging from moving, re-sizing, changing focus, being hidden by other frames, and so on and so forth. Many of these events are detected auto-magically, and paintComponent
is called internally when it is determined that that operation is necessary.
I've worked with Swing for many years, and I don't think I've ever called paintComponent
directly, or even seen it called directly from something else. The closest I've come is using the repaint()
methods to programmatically trigger a repaint of certain components (which I assume calls the correct paintComponent
methods downstream.
In my experience, paintComponent
is rarely directly overridden. I admit that there are custom rendering tasks that require such granularity, but Java Swing does offer a (fairly) robust set of JComponents and Layouts that can be used to do much of the heavy lifting without having to directly override paintComponent
. I guess my point here is to make sure that you can't do something with native JComponents and Layouts before you go off trying to roll your own custom-rendered components.
you can define a route in web.php
Route::get('/clear/route', 'ConfigController@clearRoute');
and make ConfigController.php like this
class ConfigController extends Controller
{
public function clearRoute()
{
\Artisan::call('route:clear');
}
}
and go to that route on server example http://your-domain/clear/route
For example you want to find a mean of each column in matrix. Let's create the following matrix
mat2 = np.array([1,5,6,7,3,0,3,5,9,10,8,0], dtype=np.float64).reshape(3, 4)
The function for mean is
def my_mean(x):
return sum(x)/len(x)
To do what is needed and store result in colon vector 'results'
results = np.zeros(4)
for i in range(0, 4):
mat2[:, i] = my_mean(mat2[:, i])
results = mat2[1,:]
The results are: array([4.33333333, 5. , 5.66666667, 4. ])
In my personal case, I had failed to add a reference to one of the projects in the solution and this is what was kicking up the error for me.
I'd bet that Programmer's Notepad would give you something like that...
Using table aliases in the join condition:
update addresses a
set cid = b.id
from customers b
where a.id = b.id
If using conda, you can get the env prefix using os.environ["CONDA_PREFIX"]
.
As an alternative option, if you are not married to the idea of migrations, there is a compelling gem for ActiveRecord which will handle the name changes automatically for you, Datamapper style. All you do is change the column name in your model (and make sure you put Model.auto_upgrade! at the bottom of your model.rb) and viola! Database is updated on the fly.
https://github.com/DAddYE/mini_record
Note: You will need to nuke db/schema.rb to prevent conflicts
Still in beta phases and obviously not for everyone but still a compelling choice (I am currently using it in two non-trivial production apps with no issues)
UPDATE
Angular offers now the two scope methods $watchGroup (since 1.3) and $watchCollection. Those have been mentioned by @blazemonger and @kargold.
This should work independent of the types and values:
$scope.$watch('[age,name]', function () { ... }, true);
You have to set the third parameter to true in this case.
The string concatenation 'age + name'
will fail in a case like this:
<button ng-init="age=42;name='foo'" ng-click="age=4;name='2foo'">click</button>
Before the user clicks the button the watched value would be 42foo
(42
+ foo
) and after the click 42foo
(4
+ 2foo
). So the watch function would not be called. So better use an array expression if you cannot ensure, that such a case will not appear.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="//cdn.jsdelivr.net/jasmine/1.3.1/jasmine.css" rel="stylesheet" />
<script src="//cdn.jsdelivr.net/jasmine/1.3.1/jasmine.js"></script>
<script src="//cdn.jsdelivr.net/jasmine/1.3.1/jasmine-html.js"></script>
<script src="http://code.angularjs.org/1.2.0-rc.2/angular.js"></script>
<script src="http://code.angularjs.org/1.2.0-rc.2/angular-mocks.js"></script>
<script>
angular.module('demo', []).controller('MainCtrl', function ($scope) {
$scope.firstWatchFunctionCounter = 0;
$scope.secondWatchFunctionCounter = 0;
$scope.$watch('[age, name]', function () { $scope.firstWatchFunctionCounter++; }, true);
$scope.$watch('age + name', function () { $scope.secondWatchFunctionCounter++; });
});
describe('Demo module', function () {
beforeEach(module('demo'));
describe('MainCtrl', function () {
it('watch function should increment a counter', inject(function ($controller, $rootScope) {
var scope = $rootScope.$new();
scope.age = 42;
scope.name = 'foo';
var ctrl = $controller('MainCtrl', { '$scope': scope });
scope.$digest();
expect(scope.firstWatchFunctionCounter).toBe(1);
expect(scope.secondWatchFunctionCounter).toBe(1);
scope.age = 4;
scope.name = '2foo';
scope.$digest();
expect(scope.firstWatchFunctionCounter).toBe(2);
expect(scope.secondWatchFunctionCounter).toBe(2); // This will fail!
}));
});
});
(function () {
var jasmineEnv = jasmine.getEnv();
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.specFilter = function (spec) {
return htmlReporter.specFilter(spec);
};
var currentWindowOnload = window.onload;
window.onload = function() {
if (currentWindowOnload) {
currentWindowOnload();
}
execJasmine();
};
function execJasmine() {
jasmineEnv.execute();
}
})();
</script>
</head>
<body></body>
</html>
http://plnkr.co/edit/2DwCOftQTltWFbEDiDlA?p=preview
PS:
As stated by @reblace in a comment, it is of course possible to access the values:
$scope.$watch('[age,name]', function (newValue, oldValue) {
var newAge = newValue[0];
var newName = newValue[1];
var oldAge = oldValue[0];
var oldName = oldValue[1];
}, true);
I also had the same problem and I resolved by adding the reference in one of my projects which didn't had the mentioned reference. If you have 2-3 projects in your solution, then check by adding this reference to the other projects.
"usecols" should help, use range of columns (as per excel worksheet, A,B...etc.) below are the examples
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A,C,F")
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A:F,H")
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A:F,H,J:N")
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A:N")
Another way would be to use pandas "DateOffset" class
link:-https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.tseries.offsets.DateOffset.html
Using ASGM's code(above in the answers):
from datetime import datetime
import pandas as pd
your_date_string = "April 1, 2012"
format_string = "%B %d, %Y"
datetime_object = datetime.strptime(your_date_string, format_string).date()
new_date = datetime_object + pd.DateOffset(years=1)
new_date.date()
It will return the datetime object with the added year.
Something like this:-
datetime.date(2013, 4, 1)
You can use this for 24 hour to 12 hour:
echo date("h:i", strtotime($time));
And for vice versa:
echo date("H:i", strtotime($time));
I came to this thread looking for a way to make an "atomic" commit of just some files and instead of ignoring some files on commit I went the other way and only commited the files I wanted:
svn ci filename1 filename2
Maybe, it will help someone.
To overcome the null
/ undefined
issue, try using the ?
operator to check existence:
<p ng-if="post?.capabilities?.items?.length > 0">
Sidenote, if anyone got to this page looking for an Ionic Framework answer, ensure you use *ngIf
:
<p *ngIf="post?.capabilities?.items?.length > 0">
that will do it all without css
<TABLE BORDER=1 RULES=ALL FRAME=VOID>
code from: HTML CODE TUTORIAL
The reason you are not receiving the event is because the absolutely positioned element is not a child of the element you are wanting to "click" (blue div). The cleanest way I can think of is to put the absolute element as a child of the one you want clicked, but I'm assuming you can't do that or you wouldn't have posted this question here :)
Another option would be to register a click event handler for the absolute element and call the click handler for the blue div, causing them both to flash.
Due to the way events bubble up through the DOM I'm not sure there is a simpler answer for you, but I'm very curious if anyone else has any tricks I don't know about!
cd venv
source bin/activate
export PYTHONPATH='/home/django/srmvenv/lib/python3.4'
python
\>\> import sys
\>\> sys.path
ShortcutBadger is a library that adds an abstraction layer over the device brand and current launcher and offers a great result. Works with LG, Sony, Samsung, HTC and other custom Launchers.
It even has a way to display Badge Count in Pure Android devices desktop.
Updating the Badge Count in the application icon is as easy as calling:
int badgeCount = 1;
ShortcutBadger.applyCount(context, badgeCount);
It includes a demo application that allows you to test its behavior.
What you have to do is to set the MinimumHeight property of the row. Not only the Height property. That's the key. Put the code bellow in the CellPainting event of the datagridview
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
foreach(DataGridViewRow x in dataGridView1.Rows)
{
x.MinimumHeight = 50;
}
}
For those who are looking to combine 2 color images into one, this is a slight mod on Andrey's answer which worked for me :
img1 = cv2.imread(imageFile1)
img2 = cv2.imread(imageFile2)
h1, w1 = img1.shape[:2]
h2, w2 = img2.shape[:2]
#create empty matrix
vis = np.zeros((max(h1, h2), w1+w2,3), np.uint8)
#combine 2 images
vis[:h1, :w1,:3] = img1
vis[:h2, w1:w1+w2,:3] = img2
You can make a drawable like circle, line, rectangle etc through shapes in xml as follow:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line" >
<solid android:color="#00000000" />
<stroke
android:width="2dp"
android:color="#808080" />
</shape>
To convert a field of string type to date field, you would need to iterate the cursor returned by the find()
method using the forEach()
method, within the loop convert the field to a Date object and then update the field using the $set
operator.
Take advantage of using the Bulk API for bulk updates which offer better performance as you will be sending the operations to the server in batches of say 1000 which gives you a better performance as you are not sending every request to the server, just once in every 1000 requests.
The following demonstrates this approach, the first example uses the Bulk API available in MongoDB versions >= 2.6 and < 3.2
. It updates all
the documents in the collection by changing all the created_at
fields to date fields:
var bulk = db.collection.initializeUnorderedBulkOp(),
counter = 0;
db.collection.find({"created_at": {"$exists": true, "$type": 2 }}).forEach(function (doc) {
var newDate = new Date(doc.created_at);
bulk.find({ "_id": doc._id }).updateOne({
"$set": { "created_at": newDate}
});
counter++;
if (counter % 1000 == 0) {
bulk.execute(); // Execute per 1000 operations and re-initialize every 1000 update statements
bulk = db.collection.initializeUnorderedBulkOp();
}
})
// Clean up remaining operations in queue
if (counter % 1000 != 0) { bulk.execute(); }
The next example applies to the new MongoDB version 3.2
which has since deprecated the Bulk API and provided a newer set of apis using bulkWrite()
:
var bulkOps = [];
db.collection.find({"created_at": {"$exists": true, "$type": 2 }}).forEach(function (doc) {
var newDate = new Date(doc.created_at);
bulkOps.push(
{
"updateOne": {
"filter": { "_id": doc._id } ,
"update": { "$set": { "created_at": newDate } }
}
}
);
})
db.collection.bulkWrite(bulkOps, { "ordered": true });
mysqladmin
is not a SQL statement. It's a little helper utility program you'll find on your MySQL server... and "flush-hosts" is one of the things it can do. ("status" and "shutdown" are a couple of other things that come to mind).
You type that command from a shell prompt.
Alternately, from your query browser (such as phpMyAdmin), the SQL statement you're looking for is simply this:
FLUSH HOSTS;
Extending the above post by Tom, if you need a class type declaration and access the singleton instance using a variable, the code below might be of help. I like this notation as the code is little self guiding.
function SingletonClass(){
if ( arguments.callee.instance )
return arguments.callee.instance;
arguments.callee.instance = this;
}
SingletonClass.getInstance = function() {
var singletonClass = new SingletonClass();
return singletonClass;
};
To access the singleton, you would
var singleTon = SingletonClass.getInstance();
If you happen to need this in Android and want to make it work with anything older than FroYo, you can also use EncodingUtils.getAsciiBytes():
byte[] bytes = EncodingUtils.getAsciiBytes("ASCII Text");
you can also use this code in your style.xml file so you don't need to write anything else in your activity.java
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:windowAnimationStyle">@style/AppTheme.WindowTransition</item>
</style>
<!-- Setting window animation -->
<style name="AppTheme.WindowTransition">
<item name="android:windowEnterAnimation">@android:anim/fade_in</item>
<item name="android:windowExitAnimation">@android:anim/fade_out</item>
</style>
There is a package matrixStats
that provides some functions to do column and row summaries, see in the package vignette, but you have to convert your data.frame into a matrix.
Then you run: colMaxs(as.matrix(ozone))
Other variation of Abhishek Bhalani
: You can use Array.map() instead of $.each()
var items = ['United States', 'Canada', 'Argentina', 'Armenia'];
var cList = $('ul.mylist');
items.map( (item,i ) => {
var li = $('<li/>')
.addClass('ui-menu-item')
.attr('role', 'menuitem')
.appendTo(cList);
$('<a class="ui-all">'+ i + ': ' + item.name + '<a/>')
.appendTo(li);
});
I couldn't find a rationale by the original developers this quickly, but I can give you an educated guess based on a few years of Git experience.
No, not every branch is something you want to push to the outside world. It might represent a private experiment.
Moreover, where should git push
send all the branches? Git can work with multiple remotes and you may want to have different sets of branches on each. E.g. a central project GitHub repo may have release branches; a GitHub fork may have topic branches for review; and a local Git server may have branches containing local configuration. If git push
would push all branches to the remote that the current branch tracks, this kind of scheme would be easy to screw up.
You don't need any tool. Only a few clicks.
Windows 10 can handle ttc files with no problem.
You can double click the file and install it like any ttf. Then if you nead the individual ttf files you can go to C:\Windows\Fonts\Font Name and there you will findit. If you cant do this i suspect you have a corupt file.
Here's my suggestion:
function toCamelCase(string) {
return `${string}`
.replace(new RegExp(/[-_]+/, 'g'), ' ')
.replace(new RegExp(/[^\w\s]/, 'g'), '')
.replace(
new RegExp(/\s+(.)(\w+)/, 'g'),
($1, $2, $3) => `${$2.toUpperCase() + $3.toLowerCase()}`
)
.replace(new RegExp(/\s/, 'g'), '')
.replace(new RegExp(/\w/), s => s.toLowerCase());
}
or
String.prototype.toCamelCase = function() {
return this
.replace(new RegExp(/[-_]+/, 'g'), ' ')
.replace(new RegExp(/[^\w\s]/, 'g'), '')
.replace(
new RegExp(/\s+(.)(\w+)/, 'g'),
($1, $2, $3) => `${$2.toUpperCase() + $3.toLowerCase()}`
)
.replace(new RegExp(/\s/, 'g'), '')
.replace(new RegExp(/\w/), s => s.toLowerCase());
};
Test cases:
describe('String to camel case', function() {
it('should return a camel cased string', function() {
chai.assert.equal(toCamelCase('foo bar'), 'fooBar');
chai.assert.equal(toCamelCase('Foo Bar'), 'fooBar');
chai.assert.equal(toCamelCase('fooBar'), 'fooBar');
chai.assert.equal(toCamelCase('FooBar'), 'fooBar');
chai.assert.equal(toCamelCase('--foo-bar--'), 'fooBar');
chai.assert.equal(toCamelCase('__FOO_BAR__'), 'fooBar');
chai.assert.equal(toCamelCase('!--foo-¿?-bar--121-**%'), 'fooBar121');
});
});
For casting varchar fields/values to number format can be little hack used:
SELECT (`PROD_CODE` * 1) AS `PROD_CODE` FROM PRODUCT`
hey first of all to include c++ functions you should use
include
<iostream.h>
instead of stdio .hand to hold the output screen there is a simple command getch(); here, is an example:
#include<iostream.h>
#include<conio.h>
void main() \\or int main(); if you want
{
cout<<"c# is more advanced than c++";
getch();
}
thank you
Yes, contains is case sensitive. You can use java.util.regex.Pattern with the CASE_INSENSITIVE flag for case insensitive matching:
Pattern.compile(Pattern.quote(wantedStr), Pattern.CASE_INSENSITIVE).matcher(source).find();
EDIT: If s2 contains regex special characters (of which there are many) it's important to quote it first. I've corrected my answer since it is the first one people will see, but vote up Matt Quail's since he pointed this out.
This error also happens if u forgot to include this, in your ajax submission request ( POST ), contentType: false, processData: false,
Form the Inheritance concept, If some perticular method is not available in the current class it will search for that method in super classes. If available it executes.
It executes
AbstractList<E>
classadd()
method which throwsUnsupportedOperationException
.
When you are converting from an Array to a Collection Obejct. i.e., array-based to collection-based API then it is going to provide you fixed-size collection object, because Array's behaviour is of Fixed size.
java.util.Arrays.asList( T... a )
Souce samples for conformation.
public class Arrays {
public static <T> List<T> asList(T... a) {
return new java.util.Arrays.ArrayList.ArrayList<>(a); // Arrays Inner Class ArrayList
}
//...
private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, java.io.Serializable {
//...
}
}
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
public E set(int index, E element) {
throw new UnsupportedOperationException();
}
public E remove(int index) {
throw new UnsupportedOperationException();
}
public Iterator<E> iterator() {
return new Itr();
}
private class Itr implements Iterator<E> {
//...
}
public ListIterator<E> listIterator() {
return listIterator(0);
}
private class ListItr extends Itr implements ListIterator<E> {
//...
}
}
Form the above Source you may observe that java.util.Arrays.ArrayList
class doesn't @Override add(index, element), set(index, element), remove(index)
. So, From inheritance it executes super AbstractList<E>
class add()
function which throws UnsupportedOperationException
.
As AbstractList<E>
is an abstract class it provides the implementation to iterator() and listIterator()
. So, that we can iterate over the list object.
List<String> list_of_Arrays = Arrays.asList(new String[] { "a", "b" ,"c"});
try {
list_of_Arrays.add("Yashwanth.M");
} catch(java.lang.UnsupportedOperationException e) {
System.out.println("List Interface executes AbstractList add() fucntion which throws UnsupportedOperationException.");
}
System.out.println("Arrays ? List : " + list_of_Arrays);
Iterator<String> iterator = list_of_Arrays.iterator();
while (iterator.hasNext()) System.out.println("Iteration : " + iterator.next() );
ListIterator<String> listIterator = list_of_Arrays.listIterator();
while (listIterator.hasNext()) System.out.println("Forward iteration : " + listIterator.next() );
while(listIterator.hasPrevious()) System.out.println("Backward iteration : " + listIterator.previous());
You can even create Fixed-Size array form Collections class Collections.unmodifiableList(list);
Sample Source:
public class Collections {
public static <T> List<T> unmodifiableList(List<? extends T> list) {
return (list instanceof RandomAccess ?
new UnmodifiableRandomAccessList<>(list) :
new UnmodifiableList<>(list));
}
}
A Collection
— sometimes called a container — is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data.
@see also
date.setTime( date.getTime() + days * 86400000 );
If you have direct access to the remote repo, you could always use:
git reset --soft HEAD^
This works since there is no attempt to modify the non-existent working directory. For more details please see the original answer:
How can I uncommit the last commit in a git bare repository?
>>> import os
>>> if os.path.exists("myfile.dat"):
... f = file("myfile.dat", "r+")
... else:
... f = file("myfile.dat", "w")
r+ means read/write
Why does it work in Chrome and not Firefox?
The W3 spec for CORS preflight requests clearly states that user credentials should be excluded. There is a bug in Chrome and WebKit where OPTIONS
requests returning a status of 401 still send the subsequent request.
Firefox has a related bug filed that ends with a link to the W3 public webapps mailing list asking for the CORS spec to be changed to allow authentication headers to be sent on the OPTIONS
request at the benefit of IIS users. Basically, they are waiting for those servers to be obsoleted.
How can I get the OPTIONS
request to send and respond consistently?
Simply have the server (API in this example) respond to OPTIONS
requests without requiring authentication.
Kinvey did a good job expanding on this while also linking to an issue of the Twitter API outlining the catch-22 problem of this exact scenario interestingly a couple weeks before any of the browser issues were filed.
Any MD5 will produce a good checksum to verify the file. Any of the files listed at the bottom of this page will work fine. http://en.wikipedia.org/wiki/Md5sum
The unique name identifier applies to radio buttons:
<input type="radio" />
change your checkboxes to radio and everything should be working
This is only if you want toget the first decimal
print(int(float(input()) * 10) % 10)
Or you can try this
num = float(input())
b = num - int(num)
c = b * 10
print(int(c))
I ran across this thread when searching for a timeout call on unit tests. I didn't find anything simple in the answers or 3rd party packages so I wrote the decorator below you can drop right into code:
import multiprocessing.pool
import functools
def timeout(max_timeout):
"""Timeout decorator, parameter in seconds."""
def timeout_decorator(item):
"""Wrap the original function."""
@functools.wraps(item)
def func_wrapper(*args, **kwargs):
"""Closure for function."""
pool = multiprocessing.pool.ThreadPool(processes=1)
async_result = pool.apply_async(item, args, kwargs)
# raises a TimeoutError if execution exceeds max_timeout
return async_result.get(max_timeout)
return func_wrapper
return timeout_decorator
Then it's as simple as this to timeout a test or any function you like:
@timeout(5.0) # if execution takes longer than 5 seconds, raise a TimeoutError
def test_base_regression(self):
...
Assuming that you didn't set a precision initially, it's assumed to be the maximum (38). You're reducing the precision because you're changing it from 38 to 14.
The easiest way to handle this is to rename the column, copy the data over, then drop the original column:
alter table EVAPP_FEES rename column AMOUNT to AMOUNT_OLD;
alter table EVAPP_FEES add AMOUNT NUMBER(14,2);
update EVAPP_FEES set AMOUNT = AMOUNT_OLD;
alter table EVAPP_FEES drop column AMOUNT_OLD;
If you really want to retain the column ordering, you can move the data twice instead:
alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);
update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;
update EVAPP_FEES set AMOUNT = null;
alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);
update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;
alter table EVAPP_FEES drop column AMOUNT_TEMP;
In Bjarne's words (The C++ Programming Language, 4th Edition, page 366):
Where termination is an acceptable response, an uncaught exception will achieve that because it turns into a call of terminate() (§13.5.2.5). Also, a
noexcept
specifier (§13.5.1.1) can make that desire explicit.Successful fault-tolerant systems are multilevel. Each level copes with as many errors as it can without getting too contorted and leaves the rest to higher levels. Exceptions support that view. Furthermore,
terminate()
supports this view by providing an escape if the exception-handling mechanism itself is corrupted or if it has been incompletely used, thus leaving exceptions uncaught. Similarly,noexcept
provides a simple escape for errors where trying to recover seems infeasible.double compute(double x) noexcept; { string s = "Courtney and Anya"; vector<double> tmp(10); // ... }
The vector constructor may fail to acquire memory for its ten doubles and throw a
std::bad_alloc
. In that case, the program terminates. It terminates unconditionally by invokingstd::terminate()
(§30.4.1.3). It does not invoke destructors from calling functions. It is implementation-defined whether destructors from scopes between thethrow
and thenoexcept
(e.g., for s in compute()) are invoked. The program is just about to terminate, so we should not depend on any object anyway. By adding anoexcept
specifier, we indicate that our code was not written to cope with a throw.
In my case, I execute taskkill /f /im dongleserver.exe
,
where dongleserver.exe
is my program's exe file.
Then I can able to reinstall my program already.
As already stated: closures, out of the box, cannot be serialized.
However, using the __sleep()
, __wakeup()
magic methods and reflection u CAN manually make closures serializable. For more details see extending-php-5-3-closures-with-serialization-and-reflection
This makes use of reflection and the php function eval. Do note this opens up the possibility of CODE injection, so please take notice of WHAT you are serializing.
MATLAB's FOR loop is static in nature; you cannot modify the loop variable between iterations, unlike the for(initialization;condition;increment) loop structure in other languages. This means that the following code always prints 1, 2, 3, 4, 5 regardless of the value of B.
A = 1:5;
for i = A
A = B;
disp(i);
end
If you want to be able to respond to changes in the data structure during iterations, a WHILE loop may be more appropriate --- you'll be able to test the loop condition at every iteration, and set the value of the loop variable(s) as you wish:
n = 10;
f = n;
while n > 1
n = n-1;
f = f*n;
end
disp(['n! = ' num2str(f)])
Btw, the for-each loop in Java (and possibly other languages) produces unspecified behavior when the data structure is modified during iteration. If you need to modify the data structure, you should use an appropriate Iterator instance which allows the addition and removal of elements in the collection you are iterating. The good news is that MATLAB supports Java objects, so you can do something like this:
A = java.util.ArrayList();
A.add(1);
A.add(2);
A.add(3);
A.add(4);
A.add(5);
itr = A.listIterator();
while itr.hasNext()
k = itr.next();
disp(k);
% modify data structure while iterating
itr.remove();
itr.add(k);
end
I had the same problem right now and i solved it. You must not need it anymore so I write for others:
if you use gvim on windows, you just add this in your _vimrc:
$VIMRUNTIME/mswin.vim behave mswin
else just use imap...
Here is Simple Solution And Complete Example for Uploading File Using Volley Android
1) Gradle Import
compile 'dev.dworks.libs:volleyplus:+'
2)Now Create a Class RequestManager
public class RequestManager {
private static RequestManager mRequestManager;
/**
* Queue which Manages the Network Requests :-)
*/
private static RequestQueue mRequestQueue;
// ImageLoader Instance
private RequestManager() {
}
public static RequestManager get(Context context) {
if (mRequestManager == null)
mRequestManager = new RequestManager();
return mRequestManager;
}
/**
* @param context application context
*/
public static RequestQueue getnstance(Context context) {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(context);
}
return mRequestQueue;
}
}
3)Now Create a Class to handle Request for uploading File WebService
public class WebService {
private RequestQueue mRequestQueue;
private static WebService apiRequests = null;
public static WebService getInstance() {
if (apiRequests == null) {
apiRequests = new WebService();
return apiRequests;
}
return apiRequests;
}
public void updateProfile(Context context, String doc_name, String doc_type, String appliance_id, File file, Response.Listener<String> listener, Response.ErrorListener errorListener) {
SimpleMultiPartRequest request = new SimpleMultiPartRequest(Request.Method.POST, "YOUR URL HERE", listener, errorListener);
// request.setParams(data);
mRequestQueue = RequestManager.getnstance(context);
request.addMultipartParam("token", "text", "tdfysghfhsdfh");
request.addMultipartParam("parameter_1", "text", doc_name);
request.addMultipartParam("dparameter_2", "text", doc_type);
request.addMultipartParam("parameter_3", "text", appliance_id);
request.addFile("document_file", file.getPath());
request.setFixedStreamingMode(true);
mRequestQueue.add(request);
}
}
4) And Now Call The method Like This to Hit the service
public class Main2Activity extends AppCompatActivity implements Response.ErrorListener, Response.Listener<String>{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uploadData();
}
});
}
private void uploadData() {
WebService.getInstance().updateProfile(getActivity(), "appl_doc", "appliance", "1", mChoosenFile, this, this);
}
@Override
public void onErrorResponse(VolleyError error) {
}
@Override
public void onResponse(String response) {
//Your response here
}
}
To use ES6 add babel-preset-env
and in your .babelrc
:
{
"presets": ["@babel/preset-env"]
}
Answer updated thanks to @ghanbari comment to apply babel 7.
AFAIK the files in the assets directory don't get unpacked. Instead, they are read directly from the APK (ZIP) file.
So, you really can't make stuff that expects a file accept an asset 'file'.
Instead, you'll have to extract the asset and write it to a seperate file, like Dumitru suggests:
File f = new File(getCacheDir()+"/m1.map");
if (!f.exists()) try {
InputStream is = getAssets().open("m1.map");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer);
fos.close();
} catch (Exception e) { throw new RuntimeException(e); }
mapView.setMapFile(f.getPath());
I often just open the console and look for the solution in the objects methods. Quite often it's already there:
>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello s'
Short answer: Use string.replace()
.
:q
that's a less command, actually. It uses the same commands as vi.
With Eclipse Collections, you can do the following if you have a list of type java.util.List<Integer>
:
List<Integer> integers = Lists.mutable.with(1, 2, 3, 4, 5);
int[] ints = LazyIterate.adapt(integers).collectInt(i -> i).toArray();
Assert.assertArrayEquals(new int[]{1, 2, 3, 4, 5}, ints);
If you already have an Eclipse Collections type like MutableList
, you can do the following:
MutableList<Integer> integers = Lists.mutable.with(1, 2, 3, 4, 5);
int[] ints = integers.asLazy().collectInt(i -> i).toArray();
Assert.assertArrayEquals(new int[]{1, 2, 3, 4, 5}, ints);
Note: I am a committer for Eclipse Collections
You can run php pages using php.exe
create some php file with php code and in the cmd write "[PATH to php.ext]\php.exe [path_to_file]\file.php"
To remove all spaces from the string:
let space_removed_string = (yourstring?.components(separatedBy: " ").joined(separator: ""))!
You could use "child process" module of nodejs to execute any shell commands or scripts with in nodejs. Let me show you with an example, I am running a shell script(hi.sh) with in nodejs.
hi.sh
echo "Hi There!"
node_program.js
const { exec } = require('child_process');
var yourscript = exec('sh hi.sh',
(error, stdout, stderr) => {
console.log(stdout);
console.log(stderr);
if (error !== null) {
console.log(`exec error: ${error}`);
}
});
Here, when I run the nodejs file, it will execute the shell file and the output would be:
Run
node node_program.js
output
Hi There!
You can execute any script just by mentioning the shell command or shell script in exec
callback.
Hope this helps! Happy coding :)
Here is a sample implementation:
import java.util.*;
public class MyBSTree<K,V> implements MyTree<K,V>{
private BSTNode<K,V> _root;
private int _size;
private Comparator<K> _comparator;
private int mod = 0;
public MyBSTree(Comparator<K> comparator){
_comparator = comparator;
}
public Node<K,V> root(){
return _root;
}
public int size(){
return _size;
}
public boolean containsKey(K key){
if(_root == null){
return false;
}
BSTNode<K,V> node = _root;
while (node != null){
int comparison = compare(key, node.key());
if(comparison == 0){
return true;
}else if(comparison <= 0){
node = node._left;
}else {
node = node._right;
}
}
return false;
}
private int compare(K k1, K k2){
if(_comparator != null){
return _comparator.compare(k1,k2);
}
else {
Comparable<K> comparable = (Comparable<K>)k1;
return comparable.compareTo(k2);
}
}
public V get(K key){
Node<K,V> node = node(key);
return node != null ? node.value() : null;
}
private BSTNode<K,V> node(K key){
if(_root != null){
BSTNode<K,V> node = _root;
while (node != null){
int comparison = compare(key, node.key());
if(comparison == 0){
return node;
}else if(comparison <= 0){
node = node._left;
}else {
node = node._right;
}
}
}
return null;
}
public void add(K key, V value){
if(key == null){
throw new IllegalArgumentException("key");
}
if(_root == null){
_root = new BSTNode<K, V>(key, value);
}
BSTNode<K,V> prev = null, curr = _root;
boolean lastChildLeft = false;
while(curr != null){
int comparison = compare(key, curr.key());
prev = curr;
if(comparison == 0){
curr._value = value;
return;
}else if(comparison < 0){
curr = curr._left;
lastChildLeft = true;
}
else{
curr = curr._right;
lastChildLeft = false;
}
}
mod++;
if(lastChildLeft){
prev._left = new BSTNode<K, V>(key, value);
}else {
prev._right = new BSTNode<K, V>(key, value);
}
}
private void removeNode(BSTNode<K,V> curr){
if(curr.left() == null && curr.right() == null){
if(curr == _root){
_root = null;
}else{
if(curr.isLeft()) curr._parent._left = null;
else curr._parent._right = null;
}
}
else if(curr._left == null && curr._right != null){
curr._key = curr._right._key;
curr._value = curr._right._value;
curr._left = curr._right._left;
curr._right = curr._right._right;
}
else if(curr._left != null && curr._right == null){
curr._key = curr._left._key;
curr._value = curr._left._value;
curr._right = curr._left._right;
curr._left = curr._left._left;
}
else { // both left & right exist
BSTNode<K,V> x = curr._left;
// find right-most node of left sub-tree
while (x._right != null){
x = x._right;
}
// move that to current
curr._key = x._key;
curr._value = x._value;
// delete duplicate data
removeNode(x);
}
}
public V remove(K key){
BSTNode<K,V> curr = _root;
V val = null;
while(curr != null){
int comparison = compare(key, curr.key());
if(comparison == 0){
val = curr._value;
removeNode(curr);
mod++;
break;
}else if(comparison < 0){
curr = curr._left;
}
else{
curr = curr._right;
}
}
return val;
}
public Iterator<MyTree.Node<K,V>> iterator(){
return new MyIterator();
}
private class MyIterator implements Iterator<Node<K,V>>{
int _startMod;
Stack<BSTNode<K,V>> _stack;
public MyIterator(){
_startMod = MyBSTree.this.mod;
_stack = new Stack<BSTNode<K, V>>();
BSTNode<K,V> node = MyBSTree.this._root;
while (node != null){
_stack.push(node);
node = node._left;
}
}
public void remove(){
throw new UnsupportedOperationException();
}
public boolean hasNext(){
if(MyBSTree.this.mod != _startMod){
throw new ConcurrentModificationException();
}
return !_stack.empty();
}
public Node<K,V> next(){
if(MyBSTree.this.mod != _startMod){
throw new ConcurrentModificationException();
}
if(!hasNext()){
throw new NoSuchElementException();
}
BSTNode<K,V> node = _stack.pop();
BSTNode<K,V> x = node._right;
while (x != null){
_stack.push(x);
x = x._left;
}
return node;
}
}
@Override
public String toString(){
if(_root == null) return "[]";
return _root.toString();
}
private static class BSTNode<K,V> implements Node<K,V>{
K _key;
V _value;
BSTNode<K,V> _left, _right, _parent;
public BSTNode(K key, V value){
if(key == null){
throw new IllegalArgumentException("key");
}
_key = key;
_value = value;
}
public K key(){
return _key;
}
public V value(){
return _value;
}
public Node<K,V> left(){
return _left;
}
public Node<K,V> right(){
return _right;
}
public Node<K,V> parent(){
return _parent;
}
boolean isLeft(){
if(_parent == null) return false;
return _parent._left == this;
}
boolean isRight(){
if(_parent == null) return false;
return _parent._right == this;
}
@Override
public boolean equals(Object o){
if(o == null){
return false;
}
try{
BSTNode<K,V> node = (BSTNode<K,V>)o;
return node._key.equals(_key) && ((_value == null && node._value == null) || (_value != null && _value.equals(node._value)));
}catch (ClassCastException ex){
return false;
}
}
@Override
public int hashCode(){
int hashCode = _key.hashCode();
if(_value != null){
hashCode ^= _value.hashCode();
}
return hashCode;
}
@Override
public String toString(){
String leftStr = _left != null ? _left.toString() : "";
String rightStr = _right != null ? _right.toString() : "";
return "["+leftStr+" "+_key+" "+rightStr+"]";
}
}
}
I usually combine CSS and JavaScript approaches, so that it works without JavaScript in all browsers but IE6/7, and in IE6/7 with JavaScript on (but not off), since they does not support the :last-child
pseudo-class.
$("li:last-child").addClass("last-child");
li:last-child,li.last-child{ /* ... */ }
Install ipynb from your command prompt
pip install import-ipynb
Import in your notebook file
import import_ipynb
Now use regular import command to import your file
import MyOtherNotebook
Make sure you have the last version for youtube-dl
sudo youtube-dl -U
after that you can solve this problem by installing the missing ffmpeg
on ubuntu and debian:
sudo apt-get install ffmpeg
and macOS use the command:
brew install ffmpeg
What I have done is implement List having a internal instance with all the methods delegated.
public class ContactList implements List<Contact>, Serializable {
private static final long serialVersionUID = -1862666454644475565L;
private final List<Contact> list;
public ContactList() {
super();
this.list = new ArrayList<Contact>();
}
public ContactList(List<Contact> list) {
super();
//copy and order list
List<Contact>aux= new ArrayList(list);
Collections.sort(aux);
this.list = aux;
}
public void clear() {
list.clear();
}
public boolean contains(Object object) {
return list.contains(object);
}
After, I have implemented a new method "putOrdered" which insert in the proper position if the element doesn't exist or replace just in case it exist.
public void putOrdered(Contact contact) {
int index=Collections.binarySearch(this.list,contact);
if(index<0){
index= -(index+1);
list.add(index, contact);
}else{
list.set(index, contact);
}
}
If you want to allow repeated elements just implement addOrdered instead (or both).
public void addOrdered(Contact contact) {
int index=Collections.binarySearch(this.list,contact);
if(index<0){
index= -(index+1);
}
list.add(index, contact);
}
If you want to avoid inserts you can also throw and unsupported operation exception on "add" and "set" methods.
public boolean add(Contact object) {
throw new UnsupportedOperationException("Use putOrdered instead");
}
... and also You have to be careful with ListIterator methods because they could modify your internal list. In this case you can return a copy of the internal list or again throw an exception.
public ListIterator<Contact> listIterator() {
return (new ArrayList<Contact>(list)).listIterator();
}
Try this instead.
<Window x:Class="BuildAssistantUI.BuildAssistantWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:VM="clr-namespace:BuildAssistantUI.ViewModels">
<Window.DataContext>
<VM:MainViewModel />
</Window.DataContext>
</Window>
This worked for me in Luna elementary OS
sudo apt-get install libxtst6:i386
If you have N
nodes, there are N - 1
directed edges than can lead from it (going to every other node). Therefore, the maximum number of edges is N * (N - 1)
.
You can use a cast to char to see the date results
select to_char(to_date('17-MAR-17 06.04.54','dd-MON-yy hh24:mi:ss'), 'mm/dd/yyyy hh24:mi:ss') from dual;
_x000D_
For SQL Server 2012, using Sql Server Management Studio, I found these steps from the Microsoft page useful to restore to a different database file and name: (ref: http://technet.microsoft.com/en-us/library/ms175510.aspx)
Note steps 4 and 7 are important to set so as not to overwrite the existing database.
To restore a database to a new location, and optionally rename the database
- Connect to the appropriate instance of the SQL Server Database Engine, and then in Object Explorer, click the server name to expand the server tree.
- Right-click Databases, and then click Restore Database. The Restore Database dialog box opens.
On the General page, use the Source section to specify the source and location of the backup sets to restore. Select one of the following options:
Database
Select the database to restore from the drop-down list. The list contains only databases that have been backed up according to the msdb backup history.
Note If the backup is taken from a different server, the destination server will not have the backup history information for the specified database. In this case, select Device to manually specify the file or device to restore.
Device
Click the browse (...) button to open the Select backup devices dialog box. In the Backup media type box, select one of the listed device types. To select one or more devices for the Backup media box, click Add. After you add the devices you want to the Backup media list box, click OK to return to the General page. In the Source: Device: Database list box, select the name of the database which should be restored.
Note This list is only available when Device is selected. Only databases that have backups on the selected device will be available.
- In the Destination section, the Database box is automatically populated with the name of the database to be restored. To change the name of the database, enter the new name in the Database box.
- In the Restore to box, leave the default as To the last backup taken or click on Timeline to access the Backup Timeline dialog box to manually select a point in time to stop the recovery action.
- In the Backup sets to restore grid, select the backups to restore. This grid displays the backups available for the specified location. By default, a recovery plan is suggested. To override the suggested recovery plan, you can change the selections in the grid. Backups that depend on the restoration of an earlier backup are automatically deselected when the earlier backup is deselected.
- To specify the new location of the database files, select the Files page, and then click Relocate all files to folder. Provide a new location for the Data file folder and Log file folder. Alternatively you can keep the same folders and just rename the database and log file names.
Insert Name of Segue to unwind.
Then,- (void)performSegueWithIdentifier:(NSString *)identifier sender:(id)sender.
with your segue identify.
Try:
mmatrix = np.zeros((nrows, ncols))
Since the shape parameter has to be an int or sequence of ints
http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html
Otherwise you are passing ncols
to np.zeros
as the dtype.
I had a similar problem to solve, here is a simple solution of how to pass variables to template files, the trick is to write the template file taking advantage of the variable. You need to create a dictionary (list is also possible), which holds the set of variables corresponding to each of the file. Then within the template file access them.
see below:
the template file: test_file.j2
# {{ ansible_managed }} created by [email protected]
{% set dkey = (item | splitext)[0] %}
{% set fname = test_vars[dkey].name %}
{% set fip = test_vars[dkey].ip %}
{% set fport = test_vars[dkey].port %}
filename: {{ fname }}
ip address: {{ fip }}
port: {{ fport }}
the playbook
---
#
# file: template_test.yml
# author: [email protected]
#
# description: playbook to demonstrate passing variables to template files
#
# this playbook will create 3 files from a single template, with different
# variables passed for each of the invocation
#
# usage:
# ansible-playbook -i "localhost," template_test.yml
- name: template variables testing
hosts: all
gather_facts: false
vars:
ansible_connection: local
dest_dir: "/tmp/ansible_template_test/"
test_files:
- file_01.txt
- file_02.txt
- file_03.txt
test_vars:
file_01:
name: file_01.txt
ip: 10.0.0.1
port: 8001
file_02:
name: file_02.txt
ip: 10.0.0.2
port: 8002
file_03:
name: file_03.txt
ip: 10.0.0.3
port: 8003
tasks:
- name: copy the files
template:
src: test_file.j2
dest: "{{ dest_dir }}/{{ item }}"
with_items:
- "{{ test_files }}"
Read MSDN.
it also contains a link to the args.
short answer: no, the main does not get override. when visual studio (actually the compiler) builds your exe it must declare a starting point for the assmebly, that point is the main function.
if you meant how to literary pass args then you can either run you're app from the command line with them (e.g. appname.exe param1 param2) or in the project setup, enter them (in the command line arguments in the Debug tab)
in the main you will need to read those args for example:
for (int i = 0; i < args.Length; i++)
{
string flag = args.GetValue(i).ToString();
if (flag == "bla")
{
Bla();
}
}
In my case I use chrono and c function localtime_r which is thread-safe (in opposition to std::localtime).
#include <iostream>
#include <chrono>
#include <ctime>
#include <time.h>
#include <iomanip>
int main() {
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
std::time_t currentTime = std::chrono::system_clock::to_time_t(now);
std::chrono::milliseconds now2 = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
struct tm currentLocalTime;
localtime_r(¤tTime, ¤tLocalTime);
char timeBuffer[80];
std::size_t charCount { std::strftime( timeBuffer, 80,
"%b %d %T",
¤tLocalTime)
};
if (charCount == 0) return -1;
std::cout << timeBuffer << "." << std::setfill('0') << std::setw(3) << now2.count() % 1000 << std::endl;
return 0;
}
For repeating an action in the future, there is the built in setInterval
function that you can use instead of setTimeout
.
It has a similar signature, so the transition from one to another is simple:
setInterval(function() {
// do stuff
}, duration);
Please try this way.
<table border="1">
<tr>
<th scope="col">Header</th>
<th scope="col">Header</th>
<th colspan="2">Header</th>
</tr>
<tr>
<td scope="row"> </td>
<td scope="row"> </td>
<td scope="col">Split this one</td>
<td scope="col">into two columns</td>
</tr>
</table>
SDK.INT is supported for Android 1.6 and up
SDK is supported for all versions
So I do:
String sdk_version_number = android.os.Build.VERSION.SDK;
Credits to: CommonsWare over this answer
If you're using xml background instead of IMG, just remove this :
<item>
<bitmap android:src="@drawable/YOURIMAGE"/>
</item>
from the 1st answer that @Ljdawson gave us.
How about something like this:
[Range(0.0, Double.MaxValue, ErrorMessage = "The field {0} must be greater than {1}.")]
That should do what you are looking for and you can avoid using strings.
The question is how to pass argument from child to parent component. This example is easy to use and tested:
//Child component
class Child extends React.Component {
render() {
var handleToUpdate = this.props.handleToUpdate;
return (<div><button onClick={() => handleToUpdate('someVar')}>Push me</button></div>
)
}
}
//Parent component
class Parent extends React.Component {
constructor(props) {
super(props);
var handleToUpdate = this.handleToUpdate.bind(this);
}
handleToUpdate(someArg){
alert('We pass argument from Child to Parent: \n' + someArg);
}
render() {
var handleToUpdate = this.handleToUpdate;
return (<div>
<Child handleToUpdate = {handleToUpdate.bind(this)} />
</div>)
}
}
if(document.querySelector("#demo")){
ReactDOM.render(
<Parent />,
document.querySelector("#demo")
);
}
Similar to another answer here, but change the http in the rewrite to to $scheme like so:
server {
listen 80;
server_name test.com;
rewrite ^ $scheme://www.test.com$request_uri? permanent;
}
And edit your main server block server_name variable as following:
server_name www.test.com;
I had to do this to redirect www.test.com to test.com.
DDL: Change the schema
DML: Change the data
Seems specific to MySQL limitations (rails's source code)
The issue arose because of not including jar
file as part of the project. I was just including it in tomcat lib. Using the below in web.xml
works now:
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
<init-param>
<param-name>cors.allowOrigin</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.supportsCredentials</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>cors.supportedHeaders</param-name>
<param-value>accept, authorization, origin</param-value>
</init-param>
<init-param>
<param-name>cors.supportedMethods</param-name>
<param-value>GET, POST, HEAD, OPTIONS</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
And the below in your project dependency:
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>cors-filter</artifactId>
<version>1.3.2</version>
</dependency>
VSCode is incredibly faster than VS. Files open instantly from Unity. VS is very slow. VSCode launches instantly. VS takes forever to launch.
VS can literally compile code, build apps and so on, it's a huge IDE like Unity itself or XCode. VSCode is indeed "just" a full-featured text editor. VSCode is NOT a compiler (far less a huge, build-everything system that can literally create apps and software of all types): VSCode is literally "just a text editor".
With VSCode, you DO need to install the "Visual Studio Code" package. (Not to be confused with the "Visual Studio" package.) (It seems to me that VS works fine without the VS package, but, with VS Code, you must install Unity's VSCode package.)
When you first download and install VSCode, simply open any C# file on your machine. It will instantly prompt you to install the needed C# package. This is harmless and easy.
Unfortunately VSCode generally has only one window! You cannot, really, easily drag files to separate windows. If this is important to you, you may need to go with VS.
The biggest problem with VS is that the overall concept of settings and preferences are absolutely horrible. In VS, it is all-but impossible to change the font, etc. In contrast, VSCode has FANTASTIC preferences - dead simple, never a problem.
As far as I can see, every single feature in VS which you use in Unity is present in VSCode. (So, code coloring, jump to definitions, it understands/autocompletes every single thing in Unity, it opens from Unity, double clicking something in the Unity console opens the file to that line, etc etc)
If you are used to VS. And you want to change to VSCode. It's always hard changing editors, they are so intimate, but it's pretty similar; you won't have a big heartache.
In short if you're a VS for Unity3D user,
and you're going to try VSCode...
VSCode is on the order of 19 trillion times faster in every way. It will blow your mind.
It does seem to have every feature.
Basically VS is the world's biggest IDE and application building system: VSCode is just an editor. (Indeed, that's exactly what you want with Unity, since Unity itself is the IDE.)
Don't forget to just click to install the relevant Unity package.
If I'm not mistaken, there is no reason whatsoever to use VS with Unity.
Unity is an IDE so you just need a text editor, and that is what VSCode is. VSCode is hugely better in both speed and preferences. The only possible problem - multiple-windows are a bit clunky in VSCode!
If you are using VS with Unity. There is an infuriating problem where often VS will try to open twice, that is you will end up with two or more copies of VS running. Nobody has ever been able to fix this or figure out what the hell causes it. Fortunately, this problem never happens with VSCode.
There are no installers, etc etc etc. On the download page, you download a zipped Mac app. Put it in the Applications folder and you're done.
Bizarrely there's no menu entry / docu whatsoever for folding, but here are the keys:
https://stackoverflow.com/a/30077543/294884
Particularly for Mac users who may find the colors strange:
Priceless post #1:
https://stackoverflow.com/a/45640244/294884
Priceless post #2:
https://stackoverflow.com/a/63303503/294884
To keep the "Explorer" list of files on the left tidy, in the Unity case:
Below approach of frame handling : When no id or name is given incase of nested frame
WebElement element =driver.findElement(By.xpath(".//*[@id='block-block19']//iframe"));
driver.switchTo().frame(element);
driver.findElement(By.xpath(".//[@id='carousel']/li/div/div[3]/a")).click();
I think its better you read data of text file in DataSet
Try out SqlBulkCopy - Bulk Insert into SQL from C# App
// connect to SQL
using (SqlConnection connection = new SqlConnection(connString))
{
// make sure to enable triggers
// more on triggers in next post
SqlBulkCopy bulkCopy = new SqlBulkCopy(
connection,
SqlBulkCopyOptions.TableLock |
SqlBulkCopyOptions.FireTriggers |
SqlBulkCopyOptions.UseInternalTransaction,
null
);
// set the destination table name
bulkCopy.DestinationTableName = this.tableName;
connection.Open();
// write the data in the "dataTable"
bulkCopy.WriteToServer(dataTable);
connection.Close();
}
// reset
this.dataTable.Clear();
or
after doing step 1 at the top
you can check this article for detail : Bulk Insertion of Data Using C# DataTable and SQL server OpenXML function
But its not tested with 2 million record, it will do but consume memory on machine as you have to load 2 million record and insert it.
You can check if a element is disabled or not with this:
if($("#slcCausaRechazo").prop('disabled') == false)
{
//your code to realice
}
Your local port is using by another app. I faced the same problem! You can try the following step:
Go to command line and run it as administrator!
Type:
netstat -ano | find ":5000"
=> TCP 0.0.0.0:5000 0.0.0.0:0 LISTENING 4032
TCP [::]:5000 [::]:0 LISTENING 4032
Type:
TASKKILL /F /PID 4032
=> SUCCESS: The process with PID 4032 has been terminated.
Note: My 5000 local port was listing by PID 4032. You should give yours!
The assert
statement exists in almost every programming language. It helps detect problems early in your program, where the cause is clear, rather than later as a side-effect of some other operation. They always expect a True
condition.
When you do something like:
assert condition
You're telling the program to test that condition and immediately trigger an error if it is false.
In Python, assert
expression, is equivalent to:
if __debug__:
if not <expression>: raise AssertionError
You can use the extended expression to pass an optional message:
if __debug__:
if not (expression_1): raise AssertionError(expression_2)
Try it in the Python interpreter:
>>> assert True # Nothing happens because the condition returns a True value.
>>> assert False # A traceback is triggered because this evaluation did not yield an expected value.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
There are some caveats to seen before using them mainly for those who deem to toggles between the assert
and if
statements. The aim to use assert
is on occasions when the program verifies a condition and return a value that should stop the program immediately instead of taking some alternative way to bypass the error:
As you may have noticed, the assert
statement uses two conditions. Hence, do not use parentheses to englobe them as one for obvious advice. If you do such as:
assert (condition, message)
Example:
>>> assert (1==2, 1==1)
<stdin>:1: SyntaxWarning: assertion is always true, perhaps remove parentheses?
You will be running the assert
with a (condition, message)
which represents a tuple as the first parameter, and this happens cause non-empty tuple in Python is always True
. However, you can do separately without problem:
assert (condition), "message"
Example:
>>> assert (1==2), ("This condition returns a %s value.") % "False"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: This condition returns a False value.
If you are wondering regarding when use assert
statement. Take an example used in real life:
* When your program tends to control each parameter entered by the user or whatever else:
def loremipsum(**kwargs):
kwargs.pop('bar') # return 0 if "bar" isn't in parameter
kwargs.setdefault('foo', type(self)) # returns `type(self)` value by default
assert (len(kwargs) == 0), "unrecognized parameter passed in %s" % ', '.join(kwargs.keys())
* Another case is on math when 0 or non-positive as a coefficient or constant on a certain equation:
def discount(item, percent):
price = int(item['price'] * (1.0 - percent))
print(price)
assert (0 <= price <= item['price']),\
"Discounted prices cannot be lower than 0 "\
"and they cannot be higher than the original price."
return price
* or even a simple example of a boolean implementation:
def true(a, b):
assert (a == b), "False"
return 1
def false(a, b):
assert (a != b), "True"
return 0
The utmost importance is to not rely on the assert
statement to execute data processing or data validation because this statement can be turned off on the Python initialization with -O
or -OO
flag – meaning value 1, 2, and 0 (as default), respectively – or PYTHONOPTIMIZE
environment variable.
Value 1:
* asserts are disabled;
* bytecode files are generated using .pyo
extension instead of .pyc
;
* sys.flags.optimize
is set to 1 (True
);
* and, __debug__
is set to False
;
Value 2: disables one more stuff
* docstrings are disabled;
Therefore, using the assert
statement to validate a sort of expected data is extremely dangerous, implying even to some security issues. Then, if you need to validate some permission I recommend you raise AuthError
instead. As a preconditional effective, an assert
is commonly used by programmers on libraries or modules that do not have a user interact directly.
you can use regex in order to catch any length of white space, and this would be like:
var text = "hoi how are you";
var arr = text.split(/\s+/);
console.log(arr) // will result : ["hoi", "how", "are", "you"]
console.log(arr[2]) // will result : "are"
Arrays.sort(myTypes, (a,b) -> a.name.compareTo(b.name));
Test.java
public class Test {
public static void main(String[] args) {
MyType[] myTypes = {
new MyType("John", 2, "author1", "publisher1"),
new MyType("Marry", 298, "author2", "publisher2"),
new MyType("David", 3, "author3", "publisher3"),
};
System.out.println("--- before");
System.out.println(Arrays.asList(myTypes));
Arrays.sort(myTypes, (a, b) -> a.name.compareTo(b.name));
System.out.println("--- after");
System.out.println(Arrays.asList(myTypes));
}
}
MyType.java
public class MyType {
public String name;
public int id;
public String author;
public String publisher;
public MyType(String name, int id, String author, String publisher) {
this.name = name;
this.id = id;
this.author = author;
this.publisher = publisher;
}
@Override
public String toString() {
return "MyType{" +
"name=" + name + '\'' +
", id=" + id +
", author='" + author + '\'' +
", publisher='" + publisher + '\'' +
'}' + System.getProperty("line.separator");
}
}
Output:
--- before
[MyType{name=John', id=2, author='author1', publisher='publisher1'}
, MyType{name=Marry', id=298, author='author2', publisher='publisher2'}
, MyType{name=David', id=3, author='author3', publisher='publisher3'}
]
--- after
[MyType{name=David', id=3, author='author3', publisher='publisher3'}
, MyType{name=John', id=2, author='author1', publisher='publisher1'}
, MyType{name=Marry', id=298, author='author2', publisher='publisher2'}
]
Arrays.sort(myTypes, MyType::compareThem);
where compareThem
has to be added in MyType.java:
public static int compareThem(MyType a, MyType b) {
return a.name.compareTo(b.name);
}
I ran into a similar problem while trying to code a menu for small screen sizes. The solution I went with was to just shov it off the viewport.
I made this using SASS and JQuery (No JQuery UI), but this could all be achieved in native JS and CSS.
https://codepen.io/maxbethke/pen/oNzMLRa
var menuOpen = false
var init = () => {
$(".menu__toggle, .menu__blackout").on("click", menuToggle)
}
var menuToggle = () => {
console.log("Menu:Toggle");
$(".menu__blackout").fadeToggle();
if(menuOpen) { // close menu
$(".menu__collapse").css({
left: "-80vw",
right: "100vw"
});
} else { // open menu
$(".menu__collapse").css({
left: "0",
right: "20vw"
});
}
menuOpen = !menuOpen;
}
$(document).ready(init);
_x000D_
.menu__toggle {
position: absolute;
right: 0;
z-index: 1;
}
.menu__blackout {
display: none;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(0, 0, 0, 0.5);
z-index: 10;
}
.menu__collapse {
position: absolute;
top: 0;
right: 100vw;
bottom: 0;
left: -80vw;
background: white;
-webkit-transition: ease-in-out all 1s;
transition: ease-in-out all 1s;
z-index: 11;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="menu__toggle">Toggle menu</button>
<menu class="menu">
<div class="menu__blackout"></div>
<div class="menu__collapse">
<ul class="list">
<li class="list__item">
<a class="list__item__link" href="#section1">Menu Item 1</a>
</li>
<li class="list__item">
<a class="list__item__link" href="#section2">Menu Item 2</a>
</li>
<li class="list__item">
<a class="list__item__link" href="#section3">Menu Item 3</a>
</li>
<li class="list__item">
<a class="list__item__link" href="#section4">Menu Item 4</a>
</li>
<li class="list__item">
<a class="list__item__link" href="#section5">Menu Item 5</a>
</li>
</ul>
</div>
</menu>
_x000D_
I have some code that needs to strip single or double quotes, and I can't simply ast.literal_eval it.
if len(arg) > 1 and arg[0] in ('"\'') and arg[-1] == arg[0]:
arg = arg[1:-1]
This is similar to ToolmakerSteve's answer, but it allows 0 length strings, and doesn't turn the single character "
into an empty string.
I have found this parameter -u with read.
"-u 1" means "read from stdin"
while read -r newline; do
((i++))
read -u 1 -p "Doing $i""th file, called $newline. Write your answer and press Enter!"
echo "Processing $newline with $REPLY" # united input from two different read commands.
done <<< $(ls)
Check this:
String.format(str,STR[])
For instance:
String.format( "Put your %s where your %s is", "money", "mouth" );
in a Visual Basic Macro you would use
pName = ActiveWorkbook.Path ' the path of the currently active file
wbName = ActiveWorkbook.Name ' the file name of the currently active file
shtName = ActiveSheet.Name ' the name of the currently selected worksheet
The first sheet in a workbook can be referenced by
ActiveWorkbook.Worksheets(1)
so after deleting the [Report] tab you would use
ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name
to "work on that sheet later on" you can create a range object like
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]
and continue working on MySheet(rowNum, colNum)
etc. ...
shortcut creation of a range object without defining shtName:
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]
Something like that should do the job
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith('.txt'):
print file
Why not:
<button type="submit">
<img src="mybutton.jpg" />
</button>
this code worked for me in partial view:
<a href="/Content/[email protected]">@item.Title</a>
Regex to find trailing and leading whitespaces:
^[ \t]+|[ \t]+$
Well i had the same problem what when i added the following code within the tag my problem fixed :
<head>
<meta name="viewport" content="width=device-width , initial-scale=1" />
</head>
I hope this can help you guys!
DWORD
is not a C++ type, it's defined in <windows.h>
.
The reason is that DWORD
has a specific range and format Windows functions rely on, so if you require that specific range use that type. (Or as they say "When in Rome, do as the Romans do.") For you, that happens to correspond to unsigned int
, but that might not always be the case. To be safe, use DWORD
when a DWORD
is expected, regardless of what it may actually be.
For example, if they ever changed the range or format of unsigned int
they could use a different type to underly DWORD
to keep the same requirements, and all code using DWORD
would be none-the-wiser. (Likewise, they could decide DWORD
needs to be unsigned long long
, change it, and all code using DWORD
would be none-the-wiser.)
Also note unsigned int
does not necessary have the range 0 to 4,294,967,295. See here.
As of 2011 you can use Apache Commons StringUtils.stripAccents(input) (since 3.0):
String input = StringUtils.stripAccents("Thïs iš â funky Štring");
System.out.println(input);
// Prints "This is a funky String"
Note:
The accepted answer (Erick Robertson's) doesn't work for Ø or L. Apache Commons 3.5 doesn't work for Ø either, but it does work for L. After reading the Wikipedia article for Ø, I'm not sure it should be replaced with "O": it's a separate letter in Norwegian and Danish, alphabetized after "z". It's a good example of the limitations of the "strip accents" approach.
.remove()
should remove all of them. I think the problem is that you're using an ID. There's only supposed to be one HTML element with a particular ID on the page, so jQuery is optimizing and not searching for them all. Use a class instead.
If your if statement is in Loop You can use
break;
If you want to escape some code & continue to loop Use :
continue;
If your if statement not in Loop You can use :
return 0;
Or
exit();
This one shows SQL that is currently "ACTIVE":-
select S.USERNAME, s.sid, s.osuser, t.sql_id, sql_text
from v$sqltext_with_newlines t,V$SESSION s
where t.address =s.sql_address
and t.hash_value = s.sql_hash_value
and s.status = 'ACTIVE'
and s.username <> 'SYSTEM'
order by s.sid,t.piece
/
This shows locks. Sometimes things are going slow, but it's because it is blocked waiting for a lock:
select
object_name,
object_type,
session_id,
type, -- Type or system/user lock
lmode, -- lock mode in which session holds lock
request,
block,
ctime -- Time since current mode was granted
from
v$locked_object, all_objects, v$lock
where
v$locked_object.object_id = all_objects.object_id AND
v$lock.id1 = all_objects.object_id AND
v$lock.sid = v$locked_object.session_id
order by
session_id, ctime desc, object_name
/
This is a good one for finding long operations (e.g. full table scans). If it is because of lots of short operations, nothing will show up.
COLUMN percent FORMAT 999.99
SELECT sid, to_char(start_time,'hh24:mi:ss') stime,
message,( sofar/totalwork)* 100 percent
FROM v$session_longops
WHERE sofar/totalwork < 1
/
Here it goes.
// Select by value_x000D_
$('select[name="options"]').find('option[value="3"]').attr("selected",true);_x000D_
_x000D_
// Select by text_x000D_
//$('select[name="options"]').find('option:contains("Third")').attr("selected",true);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<html>_x000D_
<body>_x000D_
<select name="options">_x000D_
<option value="1">First</option>_x000D_
<option value="2">Second</option>_x000D_
<option value="3">Third</option>_x000D_
</select>_x000D_
</body>_x000D_
</html>
_x000D_
Spring lets you define multiple contexts in a parent-child hierarchy.
The applicationContext.xml
defines the beans for the "root webapp context", i.e. the context associated with the webapp.
The spring-servlet.xml
(or whatever else you call it) defines the beans for one servlet's app context. There can be many of these in a webapp, one per Spring servlet (e.g. spring1-servlet.xml
for servlet spring1
, spring2-servlet.xml
for servlet spring2
).
Beans in spring-servlet.xml
can reference beans in applicationContext.xml
, but not vice versa.
All Spring MVC controllers must go in the spring-servlet.xml
context.
In most simple cases, the applicationContext.xml
context is unnecessary. It is generally used to contain beans that are shared between all servlets in a webapp. If you only have one servlet, then there's not really much point, unless you have a specific use for it.
timeobj = datetime.datetime.strptime(my_time, '%Y-%m-%d %I:%M:%S')
File "/usr/lib/python2.7/_strptime.py", line 335, in _strptime
data_string[found.end():])
ValueError: unconverted data remains:
In my case, the problem was an extra space in the input date string. So I used strip()
and it started to work.