You can change background-color and use !important;
.btn-primary {_x000D_
background-color: #003c79 !important;_x000D_
border-color: #15548b !important;_x000D_
color: #fff;_x000D_
}_x000D_
_x000D_
.btn-primary:hover {_x000D_
background-color: #4289c6 !important;_x000D_
border-color: #3877ae !important;_x000D_
color: #fff;_x000D_
}_x000D_
_x000D_
.btn-primary.focus, .btn-primary:focus {_x000D_
background-color: #4289c6 !important;_x000D_
border-color: #3877ae !important;_x000D_
color: #fff;_x000D_
}
_x000D_
<script language="JavaScript" type="text/javascript">
<!--
function loopSelected()
{
var txtSelectedValuesObj = document.getElementById('txtSelectedValues');
var selectedArray = new Array();
var selObj = document.getElementById('selSeaShells');
var i;
var count = 0;
for (i=0; i<selObj.options.length; i++) {
if (selObj.options[i].selected) {
selectedArray[count] = selObj.options[i].value;
count++;
}
}
txtSelectedValuesObj.value = selectedArray;
}
function openInNewWindow(frm)
{
// open a blank window
var aWindow = window.open('', 'Tutorial004NewWindow',
'scrollbars=yes,menubar=yes,resizable=yes,toolbar=no,width=400,height=400');
// set the target to the blank window
frm.target = 'Tutorial004NewWindow';
// submit
frm.submit();
}
//-->
</script>
The HTML
<form action="tutorial004_nw.html" method="get">
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<td valign="top">
<input type="button" value="Submit" onclick="openInNewWindow(this.form);" />
<input type="button" value="Loop Selected" onclick="loopSelected();" />
<br />
<select name="selSea" id="selSeaShells" size="5" multiple="multiple">
<option value="val0" selected>sea zero</option>
<option value="val1">sea one</option>
<option value="val2">sea two</option>
<option value="val3">sea three</option>
<option value="val4">sea four</option>
</select>
</td>
<td valign="top">
<input type="text" id="txtSelectedValues" />
selected array
</td>
</tr>
</table>
</form>
I provide this post for both IntelliJ and Eclipse.
Eclipse:
For making unit test for your project, please follow these steps (I am using Eclipse in order to write this test):
1- Click on New -> Java Project.
2- Write down your project name and click on finish.
3- Right click on your project. Then, click on New -> Class.
4- Write down your class name and click on finish.
Then, complete the class like this:
public class Math {
int a, b;
Math(int a, int b) {
this.a = a;
this.b = b;
}
public int add() {
return a + b;
}
}
5- Click on File -> New -> JUnit Test Case.
6- Check setUp() and click on finish. SetUp() will be the place that you initialize your test.
7- Click on OK.
8- Here, I simply add 7 and 10. So, I expect the answer to be 17. Complete your test class like this:
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class MathTest {
Math math;
@Before
public void setUp() throws Exception {
math = new Math(7, 10);
}
@Test
public void testAdd() {
Assert.assertEquals(17, math.add());
}
}
9- Write click on your test class in package explorer and click on Run as -> JUnit Test.
10- This is the result of the test.
IntelliJ: Note that I used IntelliJ IDEA community 2020.1 for the screenshots. Also, you need to set up your jre before these steps. I am using JDK 11.0.4.
1- Right-click on the main folder of your project-> new -> directory. You should call this 'test'. 2- Right-click on the test folder and create the proper package. I suggest creating the same packaging names as the original class. Then, you right-click on the test directory -> mark directory as -> test sources root. 3- In the right package in the test directory, you need to create a Java class (I suggest to use Test.java). 4- In the created class, type '@Test'. Then, among the options that IntelliJ gives you, select Add 'JUnitx' to classpath. 5- Write your test method in your test class. The method signature is like:
@Test
public void test<name of original method>(){
...
}
You can do your assertions like below:
Assertions.assertTrue(f.flipEquiv(node1_1, node2_1));
These are the imports that I added:
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
This is the test that I wrote:
You can check your methods like below:
Assertions.assertEquals(<Expected>,<actual>);
Assertions.assertTrue(<actual>);
...
For running your unit tests, right-click on the test and click on Run .
If your test passes, the result will be like below:
I hope it helps. You can see the structure of the project in GitHub https://github.com/m-vahidalizadeh/problem_solving_project.
Consider also the request timeout:
Modern browser return readyState=4 and status=0 if too much time passes before the server response.
Unit test is usually done for a single functionality implemented in Software module. The scope of testing is entirely within this SW module. Unit test never fulfils the final functional requirements. It comes under whitebox testing methodology..
Whereas Integration test is done to ensure the different SW module implementations. Testing is usually carried out after module level integration is done in SW development.. This test will cover the functional requirements but not enough to ensure system validation.
The CURL extension ext/curl
is not installed or enabled in your PHP installation. Check the manual for information on how to install or enable CURL on your system.
You can use a data:
URL to embed a Base64 encoded version of an image. But it's not very efficient and wouldn't recommend embedding large images. Any reason linking to another file is not feasible?
The bug is probably somewhere else in your code, because it should work fine:
>>> 3 not in [2, 3, 4]
False
>>> 3 not in [4, 5, 6]
True
Or with tuples:
>>> (2, 3) not in [(2, 3), (5, 6), (9, 1)]
False
>>> (2, 3) not in [(2, 7), (7, 3), "hi"]
True
Add this to your global.asax.cs:
protected void Application_PreSendRequestHeaders()
{
Response.Headers.Remove("Server");
Response.Headers.Remove("X-AspNet-Version");
Response.Headers.Remove("X-AspNetMvc-Version");
}
It's been a few years, and Chrome at least makes use of this attribute. This attribute is very useful from a usability standpoint as it will filter out the unnecessary files for the user, making their experience smoother. However, the user can still select "all files" from the type (or otherwise bypass the filter), thus you should always validate the file where it is actually used; If you're using it on the server, validate it there before using it. The user can always bypass any client-side scripting.
I had to use vbLf only in an ASP script where the original data was POSTed from a PHP script on a cPanel box over to ASP on a win server
(VBScript)
EmailText = Replace(EmailText, vbLf, "<br>")
Suppose you face this issue while running your go binary with in alpine container. Export the following variable before building your bin
# CGO has to be disabled for alpine
export CGO_ENABLED=0
Then go build
Try below:
<Spinner
android:id="@+id/YourSpinnerId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:prompt="Gender" />
I'm not really sure if I got your question right. Maybe something like
public class CommentsController : Controller
{
[HttpPost]
public ActionResult WriteComment(CommentModel comment)
{
// Do the basic model validation and other stuff
try
{
if (ModelState.IsValid )
{
// Insert the model to database like:
db.Comments.Add(comment);
db.SaveChanges();
// Pass the comment's article id to the read action
return RedirectToAction("Read", "Articles", new {id = comment.ArticleID});
}
}
catch ( Exception e )
{
throw e;
}
// Something went wrong
return View(comment);
}
}
public class ArticlesController : Controller
{
// id is the id of the article
public ActionResult Read(int id)
{
// Get the article from database by id
var model = db.Articles.Find(id);
// Return the view
return View(model);
}
}
The ssh2 functions aren't very good. Hard to use and harder yet to install, using them will guarantee that your code has zero portability. My recommendation would be to use phpseclib, a pure PHP SFTP implementation.
Check Nullable<T>.HasValue
if(!SomeProperty.HasValue ||SomeProperty.Value == Guid.Empty)
{
//not valid GUID
}
else
{
//Valid GUID
}
To push specific, one tag do following
git push origin tag_name
Even better then @Tanjim Rahman answer you can using Spring Data JPA use the method T getOne(ID id)
Customer customerToUpdate = customerRepository.getOne(id);
customerToUpdate.setName(customerDto.getName);
customerRepository.save(customerToUpdate);
Is's better because getOne(ID id)
gets you only a reference (proxy) object and does not fetch it from the DB. On this reference you can set what you want and on save()
it will do just an SQL UPDATE statement like you expect it. In comparsion when you call find()
like in @Tanjim Rahmans answer spring data JPA will do an SQL SELECT to physically fetch the entity from the DB, which you dont need, when you are just updating.
I know this question is old. But this might be useful for someone who is having the problem with legend. In addition to the answer given by ZaneDarken, I modified the chart.js file to show the legend in my pie chart. I changed the legendTemplate(which is declared many times for every chart type) just above these lines :
Chart.Type.extend({_x000D_
//Passing in a name registers this chart in the Chart namespace_x000D_
name: "Doughnut",_x000D_
//Providing a defaults will also register the deafults in the chart namespace_x000D_
defaults: defaultConfig,_x000D_
.......
_x000D_
My legendTemplate is changed from
legendTemplate : "_x000D_
<ul class=\ "<%=name.toLowerCase()%>-legend\">_x000D_
<% for (var i=0; i<datasets.length; i++){%>_x000D_
<li><span style=\ "background-color:<%=datasets[i].strokeColor%>\"></span>_x000D_
<%if(datasets[i].label){%>_x000D_
<%=datasets[i].label%>_x000D_
<%}%>_x000D_
</li>_x000D_
<%}%>_x000D_
</ul>"
_x000D_
To
legendTemplate: "_x000D_
<ul class=\ "<%=name.toLowerCase()%>-legend\">_x000D_
<% for (var i=0; i<segments.length; i++){%>_x000D_
<li><span style=\ "-moz-border-radius:7px 7px 7px 7px; border-radius:7px 7px 7px 7px; margin-right:10px;width:15px;height:15px;display:inline-block;background-color:<%=segments[i].fillColor%>\"> </span>_x000D_
<%if(segments[i].label){%>_x000D_
<%=s egments[i].label%>_x000D_
<%}%>_x000D_
</li>_x000D_
<%}%>_x000D_
</ul>"
_x000D_
One hint about HTML property placeholder and the tag textarea, please make sure there is no any space between <textarea>
and </textarea>
, otherwise the placeholder doesn't work, for example:
<textarea id="inputJSON" spellcheck="false" placeholder="JSON response string" style="flex: 1;"> </textarea>
This won't work, because there is a space between...
String and StringBuilder are actually both immutable, the StringBuilder has built in buffers which allow its size to be managed more efficiently. When the StringBuilder needs to resize is when it is re-allocated on the heap. By default it is sized to 16 characters, you can set this in the constructor.
eg.
StringBuilder sb = new StringBuilder(50);
Have a look at the respective sitepoint reference pages for background-image and URIs
Just made autocrlf
param in .gitconfig file false
and recloned the code. It worked!
[core]
autocrlf = false
You need to use these parameters in your list view:
Scroll
lv.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
Set the head of the list to it bottom
lv.setStackFromBottom(true);
You can also set these parameters in XML, eg. like this:
<ListView
...
android:transcriptMode="alwaysScroll"
android:stackFromBottom="true" />
Go to tools
>> nuget
>> console
and type:
Install-Package System.Configuration.ConfigurationManager
If you want a specific version:
Install-Package System.Configuration.ConfigurationManager -Version 4.5.0
Your ConfigurationManager
dll will now be imported and the code will begin to work.
from the debug info, it seems that the VideoIntent from the MainActivity cannot send the path of the video to VideoActivity. It gives a NullPointerException
error from the uriString
. I think some of that code from VideoActivity
:
Intent myIntent = getIntent();
String uri = myIntent.getStringExtra("uri");
Bundle b = myIntent.getExtras();
startVideo(b.getString(uri));
Cannot receive the uri from here:
public void playsquirrelmp4(View v) {
Intent VideoIntent = (new Intent(this, VideoActivity.class));
VideoIntent.putExtra("android.resource://" + getPackageName()
+ "/"+ R.raw.squirrel, uri);
startActivity(VideoIntent);
}
Using numpy.savetxt
is also an option:
import numpy as np
np.savetxt('list.txt', list, delimiter="\n", fmt="%s")
try c_x freeze it can create a good standalone
I took my chance to provide full .htaccess
code to pass on Google PageSpeed Insight:
# Enable Compression <IfModule mod_deflate.c> AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/vnd.ms-fontobject AddOutputFilterByType DEFLATE application/x-font AddOutputFilterByType DEFLATE application/x-font-opentype AddOutputFilterByType DEFLATE application/x-font-otf AddOutputFilterByType DEFLATE application/x-font-truetype AddOutputFilterByType DEFLATE application/x-font-ttf AddOutputFilterByType DEFLATE application/x-javascript AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE font/opentype AddOutputFilterByType DEFLATE font/otf AddOutputFilterByType DEFLATE font/ttf AddOutputFilterByType DEFLATE image/svg+xml AddOutputFilterByType DEFLATE image/x-icon AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/javascript AddOutputFilterByType DEFLATE text/plain </IfModule> <IfModule mod_gzip.c> mod_gzip_on Yes mod_gzip_dechunk Yes mod_gzip_item_include file .(html?|txt|css|js|php|pl)$ mod_gzip_item_include handler ^cgi-script$ mod_gzip_item_include mime ^text/.* mod_gzip_item_include mime ^application/x-javascript.* mod_gzip_item_exclude mime ^image/.* mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.* </IfModule> # Leverage Browser Caching <IfModule mod_expires.c> ExpiresActive On ExpiresByType image/jpg "access 1 year" ExpiresByType image/jpeg "access 1 year" ExpiresByType image/gif "access 1 year" ExpiresByType image/png "access 1 year" ExpiresByType text/css "access 1 month" ExpiresByType text/html "access 1 month" ExpiresByType application/pdf "access 1 month" ExpiresByType text/x-javascript "access 1 month" ExpiresByType application/x-shockwave-flash "access 1 month" ExpiresByType image/x-icon "access 1 year" ExpiresDefault "access 1 month" </IfModule> <IfModule mod_headers.c> <filesmatch "\.(ico|flv|jpg|jpeg|png|gif|css|swf)$"> Header set Cache-Control "max-age=2678400, public" </filesmatch> <filesmatch "\.(html|htm)$"> Header set Cache-Control "max-age=7200, private, must-revalidate" </filesmatch> <filesmatch "\.(pdf)$"> Header set Cache-Control "max-age=86400, public" </filesmatch> <filesmatch "\.(js)$"> Header set Cache-Control "max-age=2678400, private" </filesmatch> </IfModule>
There is also some configurations for various web servers see here.
Hope this would help to get the 100/100 score.
we can generate wsdl file from xsd but you have to use oracle enterprise pack of eclipse(OEPE). simply create xsd and then right click->new->wsdl...
The <img>
element is empty — it doesn't have an end tag.
If the image is a background image, use CSS. If it is a content image, then set position: relative
on a container, then absolutely position the image and/or text within it.
The first preserves the original stack trace of the exception, the second one replaces it with the current location.
Therefore the first is BY FAR the better.
This bash script is for N parallel threads. Each argument is a command.
trap
will kill all subprocesses when SIGINT is catched.
wait $PID_LIST
is waiting each process to complete.
When all processes have completed, the program exits.
#!/bin/bash
for cmd in "$@"; do {
echo "Process \"$cmd\" started";
$cmd & pid=$!
PID_LIST+=" $pid";
} done
trap "kill $PID_LIST" SIGINT
echo "Parallel processes have started";
wait $PID_LIST
echo
echo "All processes have completed";
Save this script as parallel_commands
and make it executable.
This is how to use this script:
parallel_commands "cmd arg0 arg1 arg2" "other_cmd arg0 arg2 arg3"
Example:
parallel_commands "sleep 1" "sleep 2" "sleep 3" "sleep 4"
Start 4 parallel sleep and waits until "sleep 4" finishes.
If that number represents milliseconds, use the Date's constructor :
var myDate = new Date(1238540400000);
i have write the answer here How to add/use libraries in Python (3.5.1) but no problem will rewrite it again
if u have or you can create a file requirements.txt
which contains the libraries that you want to install for ex:
numpy==1.14.2
Pillow==5.1.0
You gonna situate in your folder which contains that requirements.txt
in my case the path to my project is
C:\Users\LE\Desktop\Projet2_Sig_Exo3\exo 3\k-means
now just type
python -m pip install -r ./requirements.txt
and all the libararies that you want gonna install
C:\Users\LE\Desktop\Projet2_Sig_Exo3\exo 3\k-means>python -m pip install -r ./requirements.txt
You can search column before assignments:
Dim col_n as long
for i = 1 to NumCols
if Cells(1, i).Value = "column header you are looking for" Then col_n = i
next
for i = 1 to NumRows
Cells(i, col_n).Value = "PHEV"
next i
Your data
variable contains an object, not an array, and objects do not have the push
function as the error states. To do what you need you can do this:
data.country = 'IN';
Or
data['country'] = 'IN';
On v4 simply use below code in the page you want to hide the header
export default class Login extends Component {
static navigationOptions = {
header: null
}
}
refer to Stack Navigator
There is a simple example of convert enumeration to list. for this i used Collections.list(enum)
method.
public class EnumerationToList {
public static void main(String[] args) {
Vector<String> vt = new Vector<String>();
vt.add("java");
vt.add("php");
vt.add("array");
vt.add("string");
vt.add("c");
Enumeration<String> enm = vt.elements();
List<String> ll = Collections.list(enm);
System.out.println("List elements: " + ll);
}
}
Reference : How to convert enumeration to list
First get the instance of SharedPreferences using
SharedPreferences userDetails = context.getSharedPreferences("userdetails", MODE_PRIVATE);
Now to save the values in the SharedPreferences
Editor edit = userDetails.edit();
edit.putString("username", username.getText().toString().trim());
edit.putString("password", password.getText().toString().trim());
edit.apply();
Above lines will write username and password to preference
Now to to retrieve saved values from preference, you can follow below lines of code
String userName = userDetails.getString("username", "");
String password = userDetails.getString("password", "");
(NOTE: SAVING PASSWORD IN THE APP IS NOT RECOMMENDED. YOU SHOULD EITHER ENCRYPT THE PASSWORD BEFORE SAVING OR SKIP THE SAVING THE PASSWORD)
I believe you want UPSERT.
"INSERT OR REPLACE" without the additional trickery in that answer will reset any fields you don't specify to NULL or other default value. (This behavior of INSERT OR REPLACE is unlike UPDATE; it's exactly like INSERT, because it actually is INSERT; however if what you wanted is UPDATE-if-exists you probably want the UPDATE semantics and will be unpleasantly surprised by the actual result.)
The trickery from the suggested UPSERT implementation is basically to use INSERT OR REPLACE, but specify all fields, using embedded SELECT clauses to retrieve the current value for fields you don't want to change.
I always go for the second method (using the GString template), though when there are more than a couple of parameters like you have, I tend to wrap them in ${X}
as I find it makes it more readable.
Running some benchmarks (using Nagai Masato's excellent GBench module) on these methods also shows templating is faster than the other methods:
@Grab( 'com.googlecode.gbench:gbench:0.3.0-groovy-2.0' )
import gbench.*
def (foo,bar,baz) = [ 'foo', 'bar', 'baz' ]
new BenchmarkBuilder().run( measureCpuTime:false ) {
// Just add the strings
'String adder' {
foo + bar + baz
}
// Templating
'GString template' {
"$foo$bar$baz"
}
// I find this more readable
'Readable GString template' {
"${foo}${bar}${baz}"
}
// StringBuilder
'StringBuilder' {
new StringBuilder().append( foo )
.append( bar )
.append( baz )
.toString()
}
'StringBuffer' {
new StringBuffer().append( foo )
.append( bar )
.append( baz )
.toString()
}
}.prettyPrint()
That gives me the following output on my machine:
Environment
===========
* Groovy: 2.0.0
* JVM: Java HotSpot(TM) 64-Bit Server VM (20.6-b01-415, Apple Inc.)
* JRE: 1.6.0_31
* Total Memory: 81.0625 MB
* Maximum Memory: 123.9375 MB
* OS: Mac OS X (10.6.8, x86_64)
Options
=======
* Warm Up: Auto
* CPU Time Measurement: Off
String adder 539
GString template 245
Readable GString template 244
StringBuilder 318
StringBuffer 370
So with readability and speed in it's favour, I'd recommend templating ;-)
NB: If you add toString()
to the end of the GString methods to make the output type the same as the other metrics, and make it a fairer test, StringBuilder
and StringBuffer
beat the GString methods for speed. However as GString can be used in place of String for most things (you just need to exercise caution with Map keys and SQL statements), it can mostly be left without this final conversion
Adding these tests (as it has been asked in the comments)
'GString template toString' {
"$foo$bar$baz".toString()
}
'Readable GString template toString' {
"${foo}${bar}${baz}".toString()
}
Now we get the results:
String adder 514
GString template 267
Readable GString template 269
GString template toString 478
Readable GString template toString 480
StringBuilder 321
StringBuffer 369
So as you can see (as I said), it is slower than StringBuilder or StringBuffer, but still a bit faster than adding Strings...
But still lots more readable.
Updated to latest gbench, larger strings for concatenation and a test with a StringBuilder initialised to a good size:
@Grab( 'org.gperfutils:gbench:0.4.2-groovy-2.1' )
def (foo,bar,baz) = [ 'foo' * 50, 'bar' * 50, 'baz' * 50 ]
benchmark {
// Just add the strings
'String adder' {
foo + bar + baz
}
// Templating
'GString template' {
"$foo$bar$baz"
}
// I find this more readable
'Readable GString template' {
"${foo}${bar}${baz}"
}
'GString template toString' {
"$foo$bar$baz".toString()
}
'Readable GString template toString' {
"${foo}${bar}${baz}".toString()
}
// StringBuilder
'StringBuilder' {
new StringBuilder().append( foo )
.append( bar )
.append( baz )
.toString()
}
'StringBuffer' {
new StringBuffer().append( foo )
.append( bar )
.append( baz )
.toString()
}
'StringBuffer with Allocation' {
new StringBuffer( 512 ).append( foo )
.append( bar )
.append( baz )
.toString()
}
}.prettyPrint()
gives
Environment
===========
* Groovy: 2.1.6
* JVM: Java HotSpot(TM) 64-Bit Server VM (23.21-b01, Oracle Corporation)
* JRE: 1.7.0_21
* Total Memory: 467.375 MB
* Maximum Memory: 1077.375 MB
* OS: Mac OS X (10.8.4, x86_64)
Options
=======
* Warm Up: Auto (- 60 sec)
* CPU Time Measurement: On
user system cpu real
String adder 630 0 630 647
GString template 29 0 29 31
Readable GString template 32 0 32 33
GString template toString 429 0 429 443
Readable GString template toString 428 1 429 441
StringBuilder 383 1 384 396
StringBuffer 395 1 396 409
StringBuffer with Allocation 277 0 277 286
My original reply was factually incorrect and I'm glad it was removed. The code below will work under the following conditions a) you know that nobody else modified the sequence b) the sequence was modified by your session. In my case, I encountered a similar issue where I was calling a procedure which modified a value and I'm confident the assumption is true.
SELECT mysequence.CURRVAL INTO v_myvariable FROM DUAL;
Sadly, if you didn't modify the sequence in your session, I believe others are correct in stating that the NEXTVAL is the only way to go.
npm pack
+ package.json
This is what worked for me:
module project
, execute npm pack
:This will build a <package-name>-<version>.tar.gz
file.
consumer project
Ideally you can put all such files in a tmp
folder in your consumer-project
root:
package.json
:"dependencies": {
"my-package": "file:/./tmp/my-package-1.3.3.tar.gz"
}
Install
the packages:npm install
or npm i
or yarn
consumer-project's node_modules
folder.Good Luck...
Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file.
How serialization works
This illustration shows the overall process of serialization:
The object is serialized to a stream that carries the data. The stream may also have information about the object's type, such as its version, culture, and assembly name. From that stream, the object can be stored in a database, a file, or memory.
Details in Microsoft Docs.
Alerts aren't the best for displaying objects. Try console.log? If you still see Object Object in the console, use JSON.parse like this > var obj = JSON.parse(yourObject); console.log(obj)
from the terminal u can simply say
expoort FLASK_APP=app_name.py
export FLASK_ENV=development
flask run
or in ur file
if __name__ == "__main__":
app.run(debug=True)
My guess is the best you can come up with is
this.approved_by = IsNullOrEmpty(planRec.approved_by) ? string.Empty
: planRec.approved_by.ToString();
Of course since you're hinting at the fact that approved_by
is an object
(which cannot equal ""), this would be rewritten as
this.approved_by = (planRec.approved_by ?? string.Empty).ToString();
I am just beginning to dig deeper into git, so not sure if I understand correctly, but I think the correct answer to the OP's question is that you can run git log --all
with a format specification like this: git log --all --pretty=format:'%h: %s %d'
. This marks the current checked out version as (HEAD)
and you can just grab the next one from the list.
BTW, add an alias like this to your .gitconfig
with a slightly better format and you can run git hist --all
:
hist = log --pretty=format:\"%h %ai | %s%d [%an]\" --graph
Regarding the relative versions, I found this post, but it only talks about older versions, there is probably nothing to refer to the newer versions.
try
var x = parseFloat(num1) + parseFloat(num2) ;
or, depending on your needs:
var x = parseInt(num1) + parseInt(num2) ;
http://www.javascripter.net/faq/convert2.htm
You might want to pick up the book Javascript: The Good Parts, by Douglas Crockford. Javascript has a rather sizeable colleciton of gotchas! This book goes a long way towards clarifying them. See also
and Mr. Crockford's excellent essay, Javascript: The World's Most Misunderstood Programming Language.
If the content is a variable, it will be necessary to concatenate it with quotation marks. It worked for me. Like this:
itemSelected(id: number){ console.log('label contains', document.querySelector("label[for='" + id + "']")); }
# Define the types of logger and level of logging
log4j.rootLogger = DEBUG,console, FILE
# Define the File appender
log4j.appender.FILE=org.apache.log4j.FileAppender
# Define Console Appender
log4j.appender.console=org.apache.log4j.ConsoleAppender
# Define the layout for console appender. If you do not
# define it, you will get an error
log4j.appender.console.layout=org.apache.log4j.PatternLayout
# Set the name of the file
log4j.appender.FILE.File=log.out
# Set the immediate flush to true (default)
log4j.appender.FILE.ImmediateFlush=true
# Set the threshold to debug mode
log4j.appender.FILE.Threshold=debug
# Set the append to false, overwrite
log4j.appender.FILE.Append=false
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
you might want to try this. Seems to be pretty easy and works on IE6 and Moz atleast.
<div id ="show" style="background-color:Silver;width:100px;height:100px;visibility:visible;border-bottom:outset 1px black;border-right:outset 1px black;" ></div>
The general syntax is : border-[postion]:[border-style] [border-width] [border-color] | inherit
The list of available [border-style]s are :
There is no simple command to do it.
The most correct approach is to use function, like the one from docs.
Another solution (although not that safe) is to do update with returning, check which rows were updates, and insert the rest of them
Something along the lines of:
update table
set column = x.column
from (values (1,'aa'),(2,'bb'),(3,'cc')) as x (id, column)
where table.id = x.id
returning id;
assuming id:2 was returned:
insert into table (id, column) values (1, 'aa'), (3, 'cc');
Of course it will bail out sooner or later (in concurrent environment), as there is clear race condition in here, but usually it will work.
Here's a longer and more comprehensive article on the topic.
I solved this by updating my app theme to inherit from material components.
<style name="Theme.MyApp" parent="Theme.MaterialComponents.DayNight">
<!-- ... -->
</style>
To convert any object or object list into JSON, we have to use the function JsonConvert.SerializeObject.
The below code demonstrates the use of JSON in an ASP.NET environment:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace JSONFromCS
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e1)
{
List<Employee> eList = new List<Employee>();
Employee e = new Employee();
e.Name = "Minal";
e.Age = 24;
eList.Add(e);
e = new Employee();
e.Name = "Santosh";
e.Age = 24;
eList.Add(e);
string ans = JsonConvert.SerializeObject(eList, Formatting.Indented);
string script = "var employeeList = {\"Employee\": " + ans+"};";
script += "for(i = 0;i<employeeList.Employee.length;i++)";
script += "{";
script += "alert ('Name : ='+employeeList.Employee[i].Name+'
Age : = '+employeeList.Employee[i].Age);";
script += "}";
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(Page.GetType(), "JSON", script, true);
}
}
public class Employee
{
public string Name;
public int Age;
}
}
After running this program, you will get two alerts
In the above example, we have created a list of Employee object and passed it to function "JsonConvert.SerializeObject". This function (JSON library) will convert the object list into JSON format. The actual format of JSON can be viewed in the below code snippet:
{ "Maths" : [ {"Name" : "Minal", // First element
"Marks" : 84,
"age" : 23 },
{
"Name" : "Santosh", // Second element
"Marks" : 91,
"age" : 24 }
],
"Science" : [
{
"Name" : "Sahoo", // First Element
"Marks" : 74,
"age" : 27 },
{
"Name" : "Santosh", // Second Element
"Marks" : 78,
"age" : 41 }
]
}
Syntax:
{} - acts as 'containers'
[] - holds arrays
: - Names and values are separated by a colon
, - Array elements are separated by commas
This code is meant for intermediate programmers, who want to use C# 2.0 to create JSON and use in ASPX pages.
You can create JSON from JavaScript end, but what would you do to convert the list of object into equivalent JSON string from C#. That's why I have written this article.
In C# 3.5, there is an inbuilt class used to create JSON named JavaScriptSerializer.
The following code demonstrates how to use that class to convert into JSON in C#3.5.
JavaScriptSerializer serializer = new JavaScriptSerializer()
return serializer.Serialize(YOURLIST);
So, try to create a List of arrays with Questions and then serialize this list into JSON
You can set RequestParam, using generic class Integer instead of int, it will resolve your issue.
@RequestParam(value= "i", defaultValue = "20") Integer i
You should try to avoid using Singletons, but if you ever do need to, Lazy<T>
makes implementing lazy, thread-safe singletons easy:
public sealed class Singleton
{
// Because Singleton's constructor is private, we must explicitly
// give the Lazy<Singleton> a delegate for creating the Singleton.
static readonly Lazy<Singleton> instanceHolder =
new Lazy<Singleton>(() => new Singleton());
Singleton()
{
// Explicit private constructor to prevent default public constructor.
...
}
public static Singleton Instance => instanceHolder.Value;
}
Here you have a very good tutorial, that explains, how to use the new grid classes in Bootstrap 3.
It also covers mixins etc.
Just in case that the remote file needs your credential to get accessed, you can generate a System.Net.WebClient object using cmdlet New-Object to "Copy File Remotely", like so
$Source = "\\192.168.x.x\somefile.txt"
$Dest = "C:\Users\user\somefile.txt"
$Username = "username"
$Password = "password"
$WebClient = New-Object System.Net.WebClient
$WebClient.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)
$WebClient.DownloadFile($Source, $Dest)
Or if you need to upload a file, you can use UploadFile:
$Dest = "\\192.168.x.x\somefile.txt"
$Source = "C:\Users\user\somefile.txt"
$WebClient.UploadFile($Dest, $Source)
First of all, tf.train.GradientDescentOptimizer
is designed to use a constant learning rate for all variables in all steps. TensorFlow also provides out-of-the-box adaptive optimizers including the tf.train.AdagradOptimizer
and the tf.train.AdamOptimizer
, and these can be used as drop-in replacements.
However, if you want to control the learning rate with otherwise-vanilla gradient descent, you can take advantage of the fact that the learning_rate
argument to the tf.train.GradientDescentOptimizer
constructor can be a Tensor
object. This allows you to compute a different value for the learning rate in each step, for example:
learning_rate = tf.placeholder(tf.float32, shape=[])
# ...
train_step = tf.train.GradientDescentOptimizer(
learning_rate=learning_rate).minimize(mse)
sess = tf.Session()
# Feed different values for learning rate to each training step.
sess.run(train_step, feed_dict={learning_rate: 0.1})
sess.run(train_step, feed_dict={learning_rate: 0.1})
sess.run(train_step, feed_dict={learning_rate: 0.01})
sess.run(train_step, feed_dict={learning_rate: 0.01})
Alternatively, you could create a scalar tf.Variable
that holds the learning rate, and assign it each time you want to change the learning rate.
Something like:
>>> bytes.fromhex('4a4b4c').decode('utf-8')
'JKL'
Just put the actual encoding you are using.
If you are like me, and starring at your angular/ionic typescript, which looks like..
getPdf(endpoint: string): Observable<Blob> {
let url = this.url + '/' + endpoint;
let token = this.msal.accessToken;
console.log(token);
return this.http.post<Blob>(url, {
headers: new HttpHeaders(
{
'Access-Control-Allow-Origin': 'https://localhost:5100',
'Access-Control-Allow-Methods': 'POST',
'Content-Type': 'application/pdf',
'Authorization': 'Bearer ' + token,
'Accept': '*/*',
}),
//responseType: ResponseContentType.Blob,
});
}
And while you are setting options but can't seem to figure why they aren't anywhere..
Well.. if you were like me and started this post
from a copy/paste of a get
, then...
Change to:
getPdf(endpoint: string): Observable<Blob> {
let url = this.url + '/' + endpoint;
let token = this.msal.accessToken;
console.log(token);
return this.http.post<Blob>(url, null, { // <----- notice the null *****
headers: new HttpHeaders(
{
'Authorization': 'Bearer ' + token,
'Accept': '*/*',
}),
//responseType: ResponseContentType.Blob,
});
}
by_type_year_tag_filtered <- by_type_year_tag %>%
dplyr:: filter(tag_name %in% c("dplyr", "ggplot2"))
Fairly straightforward:
git remote rm origin
As for the filter-branch
question - just add --prune-empty
to your filter branch command and it'll remove any revision that doesn't actually contain any changes in your resulting repo:
git filter-branch --prune-empty --subdirectory-filter path/to/subtree HEAD
How (and why) to use display: table-cell (CSS)
I just wanted to mention, since I don't think any of the other answers did directly, that the answer to "why" is: there is no good reason, and you should probably never do this.
In my over a decade of experience in web development, I can't think of a single time I would have been better served to have a bunch of <div>
s with display
styles than to just have table elements.
The only hypothetical I could come up with is if you have tabular data stored in some sort of non-HTML-table format (eg. a CSV file). In a very specific version of this case it might be easier to just add <div>
tags around everything and then add descendent-based styles, instead of adding actual table tags.
But that's an extremely contrived example, and in all real cases I know of simply using table tags would be better.
You could initialize ReturnDate on the model before sending it to the view.
In the controller:
[HttpGet]
public ActionResult SomeAction()
{
var viewModel = new MyActionViewModel
{
ReturnDate = System.DateTime.Now
};
return View(viewModel);
}
Here is an example to call your webservice using jQuery.get:
$.get("http://domain.com/webservice.asmx", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
In the example above, we call "webservice.asmx", passing two parameters: name and time. Then, getting the service output in the call back function.
While some of the answers were very useful and informative, I thought I would write down the answer I came up with. The answer from Alex was very good, it is however limited in the sense that the height of the div needs to be hard coded in the CSS.
So the solution I came up with uses JS (no jQuery) and is actually a stripped down version (almost to the minimum) of over solutions to solve similar problems I found on Statckoverflow:
HTML
<div class="header">
<p class="menu"><a href="#S1" onclick="test('S1'); return false;">S1</a></p>
<p class="menu"><a href="#S2" onclick="test('S2'); return false;">S2</a></p>
<p class="menu"><a href="#S3" onclick="test('S3'); return false;">S3</a></p>
<p class="menu"><a href="#S4" onclick="test('S4'); return false;">S3</a></p>
</div>
<div style="width: 100%;">
<div id="S1" class="curtain">
blabla
</div>
<div id="S2" class="curtain">
blabla
</div>
<div id="S3" class="curtain">
blabla
</div>
<div id="S4" class="curtain">
blabla
</div>
</div>
NOTE THE "RETURN FALSE;" in the on click call. This is important if you want to avoid having your browser jumping to the link itself (and let the effect being managed by your JS).
JS code:
<script>
function scrollTo(to, duration) {
if (document.body.scrollTop == to) return;
var diff = to - document.body.scrollTop;
var scrollStep = Math.PI / (duration / 10);
var count = 0, currPos;
start = element.scrollTop;
scrollInterval = setInterval(function(){
if (document.body.scrollTop != to) {
count = count + 1;
currPos = start + diff * (0.5 - 0.5 * Math.cos(count * scrollStep));
document.body.scrollTop = currPos;
}
else { clearInterval(scrollInterval); }
},10);
}
function test(elID)
{
var dest = document.getElementById(elID);
scrollTo(dest.offsetTop, 500);
}
</script>
It's incredibly simple. It finds the vertical position of the div in the document using its unique ID (in the function test). Then it calls the scrollTo function passing the starting position (document.body.scrollTop) and the destination position (dest.offsetTop). It performs the transition using some sort of ease-inout curve.
Thanks everyone for your help.
Knowing a bit of coding can help you avoiding (sometimes heavy) libraries, and giving you (the programmer) more control.
In PHP 7 we can use:
ini_set('magic_quotes_runtime', 0);
instead of set_magic_quotes_runtime(0);
If anyone is looking for a solution here's how :
from selenium import webdriver
PROXY = "YOUR_PROXY_ADDRESS_HERE"
webdriver.DesiredCapabilities.FIREFOX['proxy']={
"httpProxy":PROXY,
"ftpProxy":PROXY,
"sslProxy":PROXY,
"noProxy":None,
"proxyType":"MANUAL",
"autodetect":False
}
driver = webdriver.Firefox()
driver.get('http://www.whatsmyip.org/')
In my Windows 7 box I found netbeans.conf in <Drive>:\<Program Files folder>\<NetBeans installation folder>\etc
. Thanks all.
i have seen your running code .There is one line correction in your code.
Write:
$("#wrapper").rotate(angle);
instead of:
$("#image").rotate(angle);
and you will get your desired output,hope this is what you want.
Make sure that you have the child class explicitly inherit the parent class:
public class Ext : Base { // stuff }
p $eax
works as of GDB 7.7.1
As of GDB 7.7.1, the command you've tried works:
set $eax = 0
p $eax
# $1 = 0
set $eax = 1
p $eax
# $2 = 1
This syntax can also be used to select between different union members e.g. for ARM floating point registers that can be either floating point or integers:
p $s0.f
p $s0.u
From the docs:
Any name preceded by ‘$’ can be used for a convenience variable, unless it is one of the predefined machine-specific register names.
and:
You can refer to machine register contents, in expressions, as variables with names starting with ‘$’. The names of registers are different for each machine; use info registers to see the names used on your machine.
But I haven't had much luck with control registers so far: OSDev 2012 http://f.osdev.org/viewtopic.php?f=1&t=25968 || 2005 feature request https://www.sourceware.org/ml/gdb/2005-03/msg00158.html || alt.lang.asm 2013 https://groups.google.com/forum/#!topic/alt.lang.asm/JC7YS3Wu31I
ARM floating point registers
I have had the same issue that I solved this way:
Instead of adding the meta to the current page header that caused the same error as you had:
Page.Header.Controls.Add(meta);
I used this instead:
Master.FindControl("YourHeadContentPlaceHolder").Controls.Add(meta);
and it works like a charm.
Maybe just use
window.parent
into your iframe to get the calling frame / windows. If you had multiple calling frame, you can use
window.top
Use CardView
in Recyclerview
Item Layout like this :
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
card_view:cardCornerRadius="10dp"
app:cardBackgroundColor="#ACACAC"
card_view:cardElevation="5dp"
app:contentPadding="10dp"
card_view:cardUseCompatPadding="true">
I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering
Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date
'You said time1 doesn't change, so I left it in a singe cell.
'If that is not correct, you will have to play with this some more.
time1 = Range("A6").Value
'Looping through each of our output cells.
For Each t In Range("B7:E9") 'Change these to match your real ranges.
'Looping through each departure date/time.
'(Only one row in your example. This can be adjusted if needed.)
For Each x In Range("B2:E2") 'Change these to match your real ranges.
'Check to see if our dep time corresponds to
'the matching column in our output
If t.Column = x.Column Then
'If it does, then check to see what our time value is
If x > 0 Then
time2 = x.Value
'Apply the change to the output cell.
t.Value = time1 - time2
'Exit out of this loop and move to the next output cell.
Exit For
End If
End If
'If the columns don't match, or the x value is not a time
'then we'll move to the next dep time (x)
Next x
Next t
End Sub
EDIT
I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).
A B C D E
1 LOAD_NUMBER 1 2 3 4
2 DEPARTURE_TIME_DATE 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 20:00
4 Dry_Refrig 7585.1 0 10099.8 16700
6 1/4/2012 19:30
Using the sub I got this output:
A B C D E
7 Friday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
8 Saturday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
9 Thursday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
Follow these steps in Xcode 10 to symbolicate a crash log from an app build on the same machine:
HTTP/2 supports queries multiplexing, headers compression, priority and more intelligent packet streaming management. This results in reduced latency and accelerates content download on modern web pages.
You should type this command with flag -f (force):
sudo docker volume rm -f <VOLUME NAME>
To go one step further, I assume you want to do something with these dtypes.
df.dtypes.to_dict()
comes in handy.
my_type = 'float64' #<---
dtypes = dataframe.dtypes.to_dict()
for col_nam, typ in dtypes.items():
if (typ != my_type): #<---
raise ValueError(f"Yikes - `dataframe['{col_name}'].dtype == {typ}` not {my_type}")
You'll find that Pandas did a really good job comparing NumPy classes and user-provided strings. For example: even things like 'double' == dataframe['col_name'].dtype
will succeed when .dtype==np.float64
.
From where did you get the idea that you need to free(token)
and free(tk)
? You don't. strsep()
doesn't allocate memory, it only returns pointers inside the original string. Of course, those are not pointers allocated by malloc()
(or similar), so free()
ing them is undefined behavior. You only need to free(s)
when you are done with the entire string.
Also note that you don't need dynamic memory allocation at all in your example. You can avoid strdup()
and free()
altogether by simply writing char *s = p;
.
There is no explicit Clone
button. Basically what you do is create an image, or snapshot of an existing EC2 instance, and then spin up a new instance using that snapshot.
First create an image from an existing EC2 instance.
Check your snapshots list to see if the process is completed. This usually takes around 20 minutes depending on how large your instance drive is.
Then, you need to create a new instance and use that image as the AMI.
Thanks, I used @str8up7od answer to create a function today which also checks if the input is empty:
function is_number(input) {
if(input === '')
return false;
let regex = new RegExp(/[^0-9]/, 'g');
return (input.match(regex) === null);
}
JButton
has a model which answers these question:
isArmed()
, isPressed()
, isRollOVer()
etc. Hence you can ask the model for the answer you are seeking:
if(jButton1.getModel().isPressed())
System.out.println("the button is pressed");
I create a student
table with three column id, student,age
. show you this example
declare @id int
select @id = 1
while @id >=1 and @id <= 1000
begin
insert into student values(@id, 'jack' + convert(varchar(5), @id), 12)
select @id = @id + 1
end
this is the result about the example
import numpy as np
# generate example matrix
matrix = np.random.rand(5,5)
matrix[0,:] = np.inf
matrix[2,:] = -np.inf
>>> matrix
array([[ inf, inf, inf, inf, inf],
[0.87362809, 0.28321499, 0.7427659 , 0.37570528, 0.35783064],
[ -inf, -inf, -inf, -inf, -inf],
[0.72877665, 0.06580068, 0.95222639, 0.00833664, 0.68779902],
[0.90272002, 0.37357483, 0.92952479, 0.072105 , 0.20837798]])
# find min and max values for each column, ignoring nan, -inf, and inf
mins = [np.nanmin(matrix[:, i][matrix[:, i] != -np.inf]) for i in range(matrix.shape[1])]
maxs = [np.nanmax(matrix[:, i][matrix[:, i] != np.inf]) for i in range(matrix.shape[1])]
# go through matrix one column at a time and replace + and -infinity
# with the max or min for that column
for i in range(matrix.shape[1]):
matrix[:, i][matrix[:, i] == -np.inf] = mins[i]
matrix[:, i][matrix[:, i] == np.inf] = maxs[i]
>>> matrix
array([[0.90272002, 0.37357483, 0.95222639, 0.37570528, 0.68779902],
[0.87362809, 0.28321499, 0.7427659 , 0.37570528, 0.35783064],
[0.72877665, 0.06580068, 0.7427659 , 0.00833664, 0.20837798],
[0.72877665, 0.06580068, 0.95222639, 0.00833664, 0.68779902],
[0.90272002, 0.37357483, 0.92952479, 0.072105 , 0.20837798]])
I had the same issue, couldn't find a right solution so I have manually deleted the component folder and then updated the app.module.ts file (removed the references to the deleted component) and it worked for me.
You shouldn't use CascadeType.ALL
on @ManyToOne
since entity state transitions should propagate from parent entities to child ones, not the other way around.
The @ManyToOne
side is always the Child association since it maps the underlying Foreign Key column.
Therefore, you should move the CascadeType.ALL
from the @ManyToOne
association to the @OneToMany
side, which should also use the mappedBy
attribute since it's the most efficient one-to-many table relationship mapping.
Your selector is missing a .
and though you say you want to change the border-color
- you're adding and removing a class that sets the background-color
Try this instead:
var myArray = [];
myArray.push({ id: 0, value: 1 });
myArray.push({ id: 2, value: 3 });
or will this not work for your situation?
change the port may help as 80 port is already using somewhere
vi /etc/nginx/sites-available/default
Change the port:
listen 8080 default_server;
listen [::]:8080 default_server;
And then restart the nginx server
nginx -t
service nginx restart
Another possible solution with JS
function onSelect(e) {
if (e.files.length > 5) {
alert("Only 5 files accepted.");
e.preventDefault();
}
}
You can use URL encoding to encode the newline as %0A
.
mailto:[email protected]?subject=test&body=type%20your%0Amessage%20here
While the above appears to work in many cases, user olibre points out that the RFC governing the mailto URI scheme specifies that %0D%0A
(carriage return + line feed) should be used instead of %0A
(line feed). See also: Newline Representations.
The time.time()
function returns the number of seconds since the epoch, as seconds. Note that the "epoch" is defined as the start of January 1st, 1970 in UTC. So the epoch is defined in terms of UTC and establishes a global moment in time. No matter where you are "seconds past epoch" (time.time()) returns the same value at the same moment.
Here is some sample output I ran on my computer, converting it to a string as well.
Python 2.7.3 (default, Apr 24 2012, 00:00:54)
[GCC 4.7.0 20120414 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> ts = time.time()
>>> print ts
1355563265.81
>>> import datetime
>>> st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
>>> print st
2012-12-15 01:21:05
>>>
The ts
variable is the time returned in seconds. I then converted it to a string using the datetime
library making it a string that is human readable.
ExecuteScalar will return
If you know that the first column of the resultset is a string, then to cover all bases you need to check for both null and DBNull. Something like:
object accountNumber = ...ExecuteScalar(...);
return (accountNumber == null) ? String.Empty : accountNumber.ToString();
The above code relies on the fact that DBNull.ToString returns an empty string.
If accountNumber was another type (say integer), then you'd need to be more explicit:
object accountNumber = ...ExecuteScalar(...);
return (accountNumber == null || Convert.IsDBNull(accountNumber) ?
(int) accountNumber : 0;
If you know for sure that your resultset will always have at least one row (e.g. SELECT COUNT(*)...), then you can skip the check for null.
In your case the error message "Unable to cast object of type ‘System.DBNull’ to type ‘System.String`" indicates that the first column of your result set is a DBNUll value. This is from the cast to string on the first line:
string accountNumber = (string) ... ExecuteScalar(...);
Marc_s's comment that you don't need to check for DBNull.Value is wrong.
In Angular 7/8/9
Source Link
Using Bootstrap Form
<form>
<div class="form-group">
<fieldset class="form-group">
<label>Upload Logo</label>
{{imageError}}
<div class="custom-file fileInputProfileWrap">
<input type="file" (change)="fileChangeEvent($event)" class="fileInputProfile">
<div class="img-space">
<ng-container *ngIf="isImageSaved; else elseTemplate">
<img [src]="cardImageBase64" />
</ng-container>
<ng-template #elseTemplate>
<img src="./../../assets/placeholder.png" class="img-responsive">
</ng-template>
</div>
</div>
</fieldset>
</div>
<a class="btn btn-danger" (click)="removeImage()" *ngIf="isImageSaved">Remove</a>
</form>
In Component Class
fileChangeEvent(fileInput: any) {
this.imageError = null;
if (fileInput.target.files && fileInput.target.files[0]) {
// Size Filter Bytes
const max_size = 20971520;
const allowed_types = ['image/png', 'image/jpeg'];
const max_height = 15200;
const max_width = 25600;
if (fileInput.target.files[0].size > max_size) {
this.imageError =
'Maximum size allowed is ' + max_size / 1000 + 'Mb';
return false;
}
if (!_.includes(allowed_types, fileInput.target.files[0].type)) {
this.imageError = 'Only Images are allowed ( JPG | PNG )';
return false;
}
const reader = new FileReader();
reader.onload = (e: any) => {
const image = new Image();
image.src = e.target.result;
image.onload = rs => {
const img_height = rs.currentTarget['height'];
const img_width = rs.currentTarget['width'];
console.log(img_height, img_width);
if (img_height > max_height && img_width > max_width) {
this.imageError =
'Maximum dimentions allowed ' +
max_height +
'*' +
max_width +
'px';
return false;
} else {
const imgBase64Path = e.target.result;
this.cardImageBase64 = imgBase64Path;
this.isImageSaved = true;
// this.previewImagePath = imgBase64Path;
}
};
};
reader.readAsDataURL(fileInput.target.files[0]);
}
}
removeImage() {
this.cardImageBase64 = null;
this.isImageSaved = false;
}
This is not a problem. If you wrap your .findElement call in a try-catch block and catch the StaleElementReferenceException , then you can loop and retry as many times as you need until it succeeds.
Here are some examples I wrote.
Another example from Selenide project:
public static final Condition hidden = new Condition("hidden", true) {
@Override
public boolean apply(WebElement element) {
try {
return !element.isDisplayed();
} catch (StaleElementReferenceException elementHasDisappeared) {
return true;
}
}
};
I think it's a bug when certificates are generated directly from Xcode. To resolve (at least in Xcode 6.1 / 6A1052d):
I had moved my log4j.properties into the resources folder and it worked fine for me !
Try this:
subset(studentdata, Drink=='water')
that should do it.
#include <cstdio>
#include <windows.h>
#include <tlhelp32.h>
int main( int, char *[] )
{
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (Process32First(snapshot, &entry) == TRUE)
{
while (Process32Next(snapshot, &entry) == TRUE)
{
if (stricmp(entry.szExeFile, "target.exe") == 0)
{
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);
// Do stuff..
CloseHandle(hProcess);
}
}
}
CloseHandle(snapshot);
return 0;
}
Also, if you'd like to use PROCESS_ALL_ACCESS in OpenProcess, you could try this:
#include <cstdio>
#include <windows.h>
#include <tlhelp32.h>
void EnableDebugPriv()
{
HANDLE hToken;
LUID luid;
TOKEN_PRIVILEGES tkp;
OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken);
LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid);
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Luid = luid;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hToken, false, &tkp, sizeof(tkp), NULL, NULL);
CloseHandle(hToken);
}
int main( int, char *[] )
{
EnableDebugPriv();
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (Process32First(snapshot, &entry) == TRUE)
{
while (Process32Next(snapshot, &entry) == TRUE)
{
if (stricmp(entry.szExeFile, "target.exe") == 0)
{
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);
// Do stuff..
CloseHandle(hProcess);
}
}
}
CloseHandle(snapshot);
return 0;
}
In Windows, you can use the following registry script to add "Delete SVN Folders" to your right click context menu. Run it on any directory containing those pesky files.
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\DeleteSVN]
@="Delete SVN Folders"
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\DeleteSVN\command]
@="cmd.exe /c \"TITLE Removing SVN Folders in %1 && COLOR 9A && FOR /r \"%1\" %%f IN (.svn) DO RD /s /q \"%%f\" \""
It means the CPU attempted to execute an instruction it didn't understand. This could be caused by corruption I guess, or maybe it's been compiled for the wrong architecture (in which case I would have thought the O/S would refuse to run the executable). Not entirely sure what the root issue is.
Adding both android:layout_centerInParent
and android:layout_centerVertical
work for me to center ImageView
both vertical and horizontal:
<ImageView
..
android:layout_centerInParent="true"
android:layout_centerVertical="true"
/>
This will do:
#include <fstream>
#include <iostream>
using std::fstream;
int main(int argc, char *argv[]) {
fstream file;
file.open("test.txt",std::ios::out);
file << fflush;
file.close();
}
If you have the luck to be sending a post request to the database with the files and you have the files you want to send in your DOM
you can simply check if the file in the file list is present in your DOM, and of course if it's not you just don't send that element to de DB.
On VS Code, just click the "Space: 4" on the downright corner and change it to tab when editing your Makefile.
you can set Timeout in connection string (time for Establish connection between client and sql). commandTimeout is set per command but its default time is 30 secend
If you are using JQuery with Form plugin, you can use:
$('#myForm').ajaxSubmit({
headers: {
"foo": "bar"
}
});
<button onclick=location=URL>Refresh</button>
This might look funny but it really does the trick.
Yes, just create a directory in your solution like lib/, and then add your dll to that directory in the filesystem and add it in the project (Add->Existing Item->etc). Then add the reference based on your project.
I have done this several times under svn and under cvs.
This can also happen if someone or something kills your connection using the KILL command.
If you are using jQuery, which quite a lot of people do, then you would implement the accepted answer like so:
var canvas = $("#mycanvas")[0];
var img = canvas.toDataURL("image/png");
$("#elememt-to-write-to").html('<img src="'+img+'"/>');
There is no newline, just the div
is a block element.
You can make the div
inline by adding display: inline
, which may be what you want.
you can use the like query for comparing the respective string with table vales.
select column name from table_name where column name like 'respective comparing value';
This solution worked for me.
The problem with setting location.hash
is that the page will jump to that id if it's found on the page.
The problem with window.history.pushState
is that it adds an entry to the history for each tab the user clicks. Then when the user clicks the back
button, they go to the previous tab. (this may or may not be what you want. it was not what I wanted).
For me, replaceState
was the better option in that it only replaces the current history, so when the user clicks the back
button, they go to the previous page.
$('#tab-selector').tabs({
activate: function(e, ui) {
window.history.replaceState(null, null, ui.newPanel.selector);
}
});
Check out the History API docs on MDN.
You can also use a while loop:
while (true) {
//your code
}
Reload Visual Studio with Administrator privileges. Windows Sockets (WinSock) will not allow you to create a SocketType.RAW Socket without Local Admin. And remember that your Solution will need elevated privileges to run as expected!
It works only if the frame contains page from the same domain (does not violate same-origin policy)
See this:
var iframe = $('#your_iframe').contents();
iframe.find('your_clicable_item').click(function(event){
console.log('work fine');
});
To know why M$ invents OLEDB, you can't compare OLEDB with ODBC. Instead, you should compare OLEDB with DAO,RDO, or ADO. The latter largely relies on SQL. However, OLEDB relies on COM. But ODBC is already there many years, so there's a OLEDB-ODBC bridges to remedy this. I think there's a big picture when M$ invents OLEDB.
You could use my tool uhubctl to control USB power per port for compatible USB hubs.
Use position: fixed
, and anchor it to the top
and right
sides of the page:
#fixed-div {
position: fixed;
top: 1em;
right: 1em;
}
IE6 does not support position: fixed
, however. If you need this functionality in IE6, this purely-CSS solution seems to do the trick. You'll need a wrapper <div>
to contain some of the styles for it to work, as seen in the stylesheet.
You don't have to handcode this. The problem definition is precisely the behavior of Apache Commons CollectionUtils#collate. It's also overloaded for different sort orders and allowing duplicates.
To get this to work I had to combine many of the above answers, to anyone who this might help here is my much simpler process.
If you have Windows 10 just start typing "edit environmental..." and it'll pop up right away. Click path and Edit… then paste the ;C:\Program Files\Git\bin\git.exe;C:\Program Files\Git\cmd
at the end of the path already there, don't forget the ; to separate your new github path from the current path.
You do not need the guid but if you want to know how to find it open bash, type git --man-path
You can just create an Image
object and put the base64 as its src
, including the data:image...
part like this:
var image = new Image();
image.src = 'data:image/png;base64,iVBORw0K...';
document.body.appendChild(image);
It's what they call "Data URIs" and here's the compatibility table for inner peace.
You can use:
input[type=text]
{
/*Styles*/
}
Define your common style attributes inside this. and for extra style you can add a class then.
EOF
is just a macro with a value (usually -1). You have to test something against EOF
, such as the result of a getchar()
call.
One way to test for the end of a stream is with the feof
function.
if (feof(stdin))
Note, that the 'end of stream' state will only be set after a failed read.
In your example you should probably check the return value of scanf and if this indicates that no fields were read, then check for end-of-file.
From the help page for ?toupper
:
.simpleCap <- function(x) {
s <- strsplit(x, " ")[[1]]
paste(toupper(substring(s, 1,1)), substring(s, 2),
sep="", collapse=" ")
}
> sapply(name, .simpleCap)
zip code state final count
"Zip Code" "State" "Final Count"
You have entered wrong port number 3360 instead of 3306. You dont need to write database port number if you are using daefault (3306 in case of MySQL)
I wrote this javascript script and included it in the header (before anything loads). It seems to work. If the page was loaded more than one hour ago or the situation is undefined it will reload everything from server. The time of one hour = 3600000 milliseconds can be changed in the following line: if(alter > 3600000)
With regards, Birke
<script type="text/javascript">
//<![CDATA[
function zeit()
{
if(document.cookie)
{
a = document.cookie;
cookiewert = "";
while(a.length > 0)
{
cookiename = a.substring(0,a.indexOf('='));
if(cookiename == "zeitstempel")
{
cookiewert = a.substring(a.indexOf('=')+1,a.indexOf(';'));
break;
}
a = a.substring(a.indexOf(cookiewert)+cookiewert.length+1,a.length);
}
if(cookiewert.length > 0)
{
alter = new Date().getTime() - cookiewert;
if(alter > 3600000)
{
document.cookie = "zeitstempel=" + new Date().getTime() + ";";
location.reload(true);
}
else
{
return;
}
}
else
{
document.cookie = "zeitstempel=" + new Date().getTime() + ";";
location.reload(true);
}
}
else
{
document.cookie = "zeitstempel=" + new Date().getTime() + ";";
location.reload(true);
}
}
zeit();
//]]>
</script>
e.target
is what triggers the event dispatcher to trigger and e.currentTarget
is what you assigned your listener to.
Try This Please
mb_substr($description, 0, 490, "UTF-8");
You can also check the default buffer size by calling the read only DEFAULT_BUFFER_SIZE attribute from io module.
import io
print (io.DEFAULT_BUFFER_SIZE)
Try this one:
$(document).ready(function() {
$(".tab").click(function () {
$("this").addClass("active").siblings().removeClass("active");
});
});
It seems like you are expecting int
and unsigned int
to be a 16-bit integer. That's apparently not the case. Most likely, it's a 32-bit integer - which is large enough to avoid the wrap-around that you're expecting.
Note that there is no fully C-compliant way to do this because casting between signed/unsigned for values out of range is implementation-defined. But this will still work in most cases:
unsigned int x = 65529;
int y = (short) x; // If short is a 16-bit integer.
or alternatively:
unsigned int x = 65529;
int y = (int16_t) x; // This is defined in <stdint.h>
This is what I used to start and stop tomcat 7.0.29, using ant 1.8.2. Works fine for me, but leaves the control in the started server window. I have not tried it yet, but I think if I change the "/K" in the startup sequence to "/C", it may not even do that.
<target name="tomcat-stop">
<exec dir="${appserver.home}/bin" executable="cmd">
<arg line="/C start cmd.exe /C shutdown.bat"/>
</exec>
</target>
<target name="tomcat-start" depends="tomcat-stop" >
<exec dir="${appserver.home}/bin" executable="cmd">
<arg line="/K start cmd.exe /C startup.bat"/>
</exec>
</target>
After installation of Oracle Client 11.02.04, reboot the server and make sure USERS(Local Computer) is added with Full Control on Root folder for eg WWW
Tested, it worked.
If you have access to the remote repo from a shell, just go into the .git (or the main dir if its a bare repo) and change the HEAD file to point to the correct head. For example, by default it always contains 'refs: refs/heads/master', but if you need foo to be the HEAD instead, just edit the HEAD file and change the contents to 'refs: refs/heads/foo'.
Java is not call by reference it is call by value only
But all variables of object type are actually pointers.
So if you use a Mutable Object you will see the behavior you want
public class XYZ {
public static void main(String[] arg) {
StringBuilder toyNumber = new StringBuilder("5");
play(toyNumber);
System.out.println("Toy number in main " + toyNumber);
}
private static void play(StringBuilder toyNumber) {
System.out.println("Toy number in play " + toyNumber);
toyNumber.append(" + 1");
System.out.println("Toy number in play after increement " + toyNumber);
}
}
Output of this code:
run:
Toy number in play 5
Toy number in play after increement 5 + 1
Toy number in main 5 + 1
BUILD SUCCESSFUL (total time: 0 seconds)
You can see this behavior in Standard libraries too. For example Collections.sort(); Collections.shuffle(); These methods does not return a new list but modifies it's argument object.
List<Integer> mutableList = new ArrayList<Integer>();
mutableList.add(1);
mutableList.add(2);
mutableList.add(3);
mutableList.add(4);
mutableList.add(5);
System.out.println(mutableList);
Collections.shuffle(mutableList);
System.out.println(mutableList);
Collections.sort(mutableList);
System.out.println(mutableList);
Output of this code:
run:
[1, 2, 3, 4, 5]
[3, 4, 1, 5, 2]
[1, 2, 3, 4, 5]
BUILD SUCCESSFUL (total time: 0 seconds)
You can also use Bash on Ubuntu on Windows
directly. E.g.,
bash -c "ssh -t user@computer 'cd /; sudo my-command'"
Per Martin Prikryl's comment below:
The -t enables terminal emulation. Whether you need the terminal emulation for sudo depends on configuration (and by default you do no need it, while many distributions override the default). On the contrary, many other commands need terminal emulation.
You can install it by first extracting all the files from the ISO and then overwriting those files with the files from the ZIP. Then you can run the batch file as administrator to do the installation. Most of the packages install on windows 7, but I haven't tested yet how well they work.
Building on @user308827's answer: you can use legend=False
in factorplot and specify the legend through matplotlib:
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="whitegrid")
titanic = sns.load_dataset("titanic")
g = sns.factorplot("class", "survived", "sex",
data=titanic, kind="bar",
size=6, palette="muted",
legend=False)
g.despine(left=True)
plt.legend(loc='upper left')
g.set_ylabels("survival probability")
you don’t need a select … from dual
, just write:
SELECT t.*, dbms_random.value(1,9) RandomNumber
FROM myTable t
I am from .net background. However, java/c# are more/less same.
If you instantiate a non-primitive type (array in your case), it won't be null.
e.g. int[] numbers = new int[3];
In this case, the space is allocated & each of the element has a default value of 0.
It will be null
, when you don't new
it up.
e.g.
int[] numbers = null; // changed as per @Joachim's suggestion.
if (numbers == null)
{
System.out.println("yes, it is null. Please new it up");
}
There are three ways
1) This runs the GUI editor for the user environment variables. It does exactly what the OP wanted to do and does not prompt for administrative credentials.
rundll32.exe sysdm.cpl,EditEnvironmentVariables
(bonus: This works on Windows Vista to Windows 10 for desktops and Windows Server 2008 through Server 2016. It does not work on Windows NT, 2000, XP, and 2003. However, on the older systems you can use sysdm.cpl without the ",EditEnvironmentVariables" parameter and then navigate to the Advanced tab and then Environment Variables button.)
2) Use the SETX command from the command prompt. This is like the set command but updates the environment that's stored in the registry. Unfortunately, SETX is not as easy to use as the built in SET command. There's no way to list the variables for example. Thus it's impossible to do something such as appending a folder to the user's PATH variable. While SET will display the variables you don't know which ones are user vs. system variables and the PATH that's shown is a combination of both.
3) Use regedit and navigate to HKEY_CURRENT_USER\Environment
Keep in mind that changes to the user's environment does not immediately propagate to all processes currently running for that user. You can see this in a command prompt where your changes will not be visible if you use SET. For example
rem Add a user environment variable named stackoverflow that's set to "test"
setx stackoverflow test
set st
This should show all variables whose names start with the letters "st". If there are none then it displays "Environment variable st not defined
".
Exit the command prompt and start another. Try set st
again
and you'll see
stackoverflow=test
To delete the stackoverflow variable use
setx stackoverflow ""
It will respond with "SUCCESS: Specified value was saved.
" which looks strange given you want to delete the variable. However, if you start a new command prompt then set st
will show that there are no variables starting with the letters "st"
(correction - I discovered that setx stackoverflow ""
did not delete the variable. It's in the registry as an empty string. The SET
command though interprets it as though there is no variable. if not defined stackoverflow echo Not defined
says it's not defined.)
Try the below:
testlist = [1,2,3,5,3,1,2,1,6]
position=0
for i in testlist:
if i == 1:
print(position)
position=position+1
This is not "auto-completion", this is automation. One common tool for these things is called Expect.
You might also get away with just piping input from yes
.
setInterval()
setInterval is a time interval based code execution method that has the native ability to repeatedly run specified script when the interval is reached. It should not be nested into its callback function by the script author to make it loop, since it loops by default. It will keep firing at the interval unless you call clearInterval().
if you want to loop code for animations or clocks Then use setInterval.
function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setInterval(doStuff, 5000);
setTimeout()
setTimeout is a time based code execution method that will execute script only one time when the interval is reached, and not repeat again unless you gear it to loop the script by nesting the setTimeout object inside of the function it calls to run. If geared to loop, it will keep firing at the interval unless you call clearTimeout().
function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setTimeout(doStuff, 5000);
if you want something to happen one time after some seconds Then use setTimeout... because it only executes one time when the interval is reached.
You're apparently off by one day, exactly 86400 seconds. Use the number 2209161600 Not the number 2209075200 If you Google the two numbers, you'll find support for the above. I tried your formula but was always coming up 1 day different from my server. It's not obvious from the unix timestamp unless you think in unix instead of human time ;-) but if you double check then you'll see this might be correct.
In my case, the table's id column was not set as an Identity column.
We use a script which checks if a running container is started with the latest image. We also use upstart init scripts for starting the docker image.
#!/usr/bin/env bash
set -e
BASE_IMAGE="registry"
REGISTRY="registry.hub.docker.com"
IMAGE="$REGISTRY/$BASE_IMAGE"
CID=$(docker ps | grep $IMAGE | awk '{print $1}')
docker pull $IMAGE
for im in $CID
do
LATEST=`docker inspect --format "{{.Id}}" $IMAGE`
RUNNING=`docker inspect --format "{{.Image}}" $im`
NAME=`docker inspect --format '{{.Name}}' $im | sed "s/\///g"`
echo "Latest:" $LATEST
echo "Running:" $RUNNING
if [ "$RUNNING" != "$LATEST" ];then
echo "upgrading $NAME"
stop docker-$NAME
docker rm -f $NAME
start docker-$NAME
else
echo "$NAME up to date"
fi
done
And init looks like
docker run -t -i --name $NAME $im /bin/bash
Same problem, I have just purged cache
rm -rf var/cache/*
Et voila ! I don't understand what it was...
The .NET framework uses banker's rounding in Math.Round
by default. You should use this overload:
Math.Round(0.5d, MidpointRounding.AwayFromZero) //1
Math.Round(0.4d, MidpointRounding.AwayFromZero) //0
Embedded option:
Wrap python code in a bash function.
#!/bin/bash
function current_datetime {
python - <<END
import datetime
print datetime.datetime.now()
END
}
# Call it
current_datetime
# Call it and capture the output
DT=$(current_datetime)
echo Current date and time: $DT
Use environment variables, to pass data into to your embedded python script.
#!/bin/bash
function line {
PYTHON_ARG="$1" python - <<END
import os
line_len = int(os.environ['PYTHON_ARG'])
print '-' * line_len
END
}
# Do it one way
line 80
# Do it another way
echo $(line 80)
http://bhfsteve.blogspot.se/2014/07/embedding-python-in-bash-scripts.html
You can simply copy it to an array:
int[] arr = new int[list.size()];
for(int i = 0; i < list.size(); i++) {
arr[i] = list.get(i);
}
Not too fancy; but, hey, it works...
You need a root node
<?xml version="1.0" encoding="ISO-8859-1"?>
<documents>
<document>
<name>Sample Document</name>
<type>document</type>
<url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&titletype=Title&fontsize=9&fontface=Arial&spacing=1.0&text=&wordcount3=0</url>
</document>
<document>
<name>Sample</name>
<type>document</type>
<url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&titletype=Title&fontsize=9&fontface=Arial&spacing=1.0&text=&</url>
</document>
</documents>
Because Xcode subsumes the CLI tools if installed first, I use the following hybrid which has been validated on 10.12 and 10.14. I expect it works on a lot of other versions:
installed=$(pkgutil --pkg-info=com.apple.pkg.CLTools_Executables 2>/dev/null || pkgutil --pkg-info=com.apple.pkg.Xcode)
Salt with awk
to taste for branching logic.
Of course xcode-select -p
handles the variations with a really short command but fails to give the detailed package, version, and installation date metadata.
I had the same issue and this piece of code worked out for me.
names(data)[names(data) == "oldVariableName"] <- "newVariableName"
In short, this code does the following:
names(data)
looks into all the names in the dataframe (data
)
[names(data) == oldVariableName]
extracts the variable name (oldVariableName
) you want to get renamed and <- "newVariableName"
assigns the new variable name.
Watch your trailing slashes too. I found that including images/*
in my ignore setting file did not ignore ./images/
. When I ran svn status -u
it still showed ? images
. So, I just changed the ignore setting to just images
, no slashes. Ran a status check and that cleared it out.
Read the Request.Form NameValueCollection and process your logic accordingly:
NameValueCollection nvc = Request.Form;
string userName, password;
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
userName = nvc["txtUserName"];
}
if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
password = nvc["txtPassword"];
}
//Process login
CheckLogin(userName, password);
... where "txtUserName" and "txtPassword" are the Names of the controls on the posting page.
@ is a shortcut option for v-on. Use @ only when you want to execute some Vue methods. As you are not executing Vue methods, instead you are calling javascript function, you need to use onchange attribute to call javascript function
<select name="LeaveType" onchange="onChange(this.value)" class="form-control">
<option value="1">Annual Leave/ Off-Day</option>
<option value="2">On Demand Leave</option>
</select>
function onChange(value) {
console.log(value);
}
If you want to call Vue methods, do it like this-
<select name="LeaveType" @change="onChange($event)" class="form-control">
<option value="1">Annual Leave/ Off-Day</option>
<option value="2">On Demand Leave</option>
</select>
new Vue({
...
...
methods:{
onChange:function(event){
console.log(event.target.value);
}
}
})
You can use v-model data attribute on the select element to bind the value.
<select v-model="selectedValue" name="LeaveType" onchange="onChange(this.value)" class="form-control">
<option value="1">Annual Leave/ Off-Day</option>
<option value="2">On Demand Leave</option>
</select>
new Vue({
data:{
selectedValue : 1, // First option will be selected by default
},
...
...
methods:{
onChange:function(event){
console.log(this.selectedValue);
}
}
})
Hope this Helps :-)
I don't know how to get a list of the parameters but you can do this to get how many it expects.
alert(doSomething.length);
There's also TryParse.
From MSDN:
private static void TryToParse(string value)
{
int number;
bool result = Int32.TryParse(value, out number);
if (result)
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
{
if (value == null) value = "";
Console.WriteLine("Attempted conversion of '{0}' failed.", value);
}
}
Just add a "multidex-config.txt" in you app directory:
Improving Suman.hassan95's answer by adding a link to subcategory as well. Replace the following code:
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo $sub_category->name ;
}
}
with:
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
}
}
or if you also wish a counter for each subcategory, replace with this:
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
echo apply_filters( 'woocommerce_subcategory_count_html', ' <span class="cat-count">' . $sub_category->count . '</span>', $category );
}
}
Note that sort() operates on the array in place, so you only need to call
sort($a);
doSomething($a);
This will not work;
$a = sort($a);
doSomething($a);
Found a way, thanks to the link here (with the original google group discussion here)
First, Telnet
to your server:
telnet 127.0.0.1 11211
Next, list the items to get the slab ids:
stats items STAT items:3:number 1 STAT items:3:age 498 STAT items:22:number 1 STAT items:22:age 498 END
The first number after ‘items’ is the slab id. Request a cache dump for each slab id, with a limit for the max number of keys to dump:
stats cachedump 3 100 ITEM views.decorators.cache.cache_header..cc7d9 [6 b; 1256056128 s] END stats cachedump 22 100 ITEM views.decorators.cache.cache_page..8427e [7736 b; 1256056128 s] END
You can do a div over the padding as follows:
<div id= "paddingOne">
</div>
<div id= "paddingTwo">
</div>
#paddingOne {
width: 100;
length: 100;
background-color: #000000;
margin: 0;
z-index: 2;
}
#paddingTwo {
width: 200;
length: 200;
background-color: #ffffff;
margin: 0;
z-index: 3;
the width, length, background color, margins, and z-index can vary of course, but in order to cover the padding, the z-index must be higher than 0 so that it will lay over the padding. You can fiddle with positioning and such to change its orientation. Hope that helps!
P.S. the divs are html and the #paddingOne and #paddingTwo are css (in case anyone didn't get that:)
It appears that a number of people misunderstand what the differences between NULL, '\0' and 0 are. So, to explain, and in attempt to avoid repeating things said earlier:
A constant expression of type int
with the value 0, or an expression of this type, cast to type void *
is a null pointer constant, which if converted to a pointer becomes a null pointer. It is guaranteed by the standard to compare unequal to any pointer to any object or function.
NULL
is a macro, defined in as a null pointer constant.
\0
is a construction used to represent the null character, used to terminate a string.
A null character is a byte which has all its bits set to 0.
You can do injection on Directives, and it looks just like it does everywhere else.
app.directive('changeIt', ['myData', function(myData){
return {
restrict: 'C',
link: function (scope, element, attrs) {
scope.name = myData.name;
}
}
}]);
A facade should not be described as a class which contains a lot of other classes. It is in fact a interface to this classes and should make the usage of the classes easier otherwise the facade class is useless.
You can use the sequence method list.extend
to extend the list by multiple values from any kind of iterable, being it another list or any other thing that provides a sequence of values.
>>> lst = [1, 2]
>>> lst.append(3)
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]
>>> lst.extend([5, 6, 7])
>>> lst.extend((8, 9, 10))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> lst.extend(range(11, 14))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
So you can use list.append()
to append a single value, and list.extend()
to append multiple values.
first I tried the code below and it was not working
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
rkApp.SetValue("MyAPP", Application.ExecutablePath.ToString());
Then, I changed CurrentUser with LocalMachine and it works
RegistryKey rkApp = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
rkApp.SetValue("MyAPP", Application.ExecutablePath.ToString());
From a std::string you can use the c_ptr() method if you want to get at the char_t buffer pointer.
It looks like you just want copy the characters of the string into a new buffer. I would simply use the std::string::copy function:
length = str.copy( buffer, str.size() );
Roland's answer needs updating. See: https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs
This method has been updated for ggplot2 v1.0.0.
library(ggplot2)
library(gridExtra)
library(grid)
grid_arrange_shared_legend <- function(...) {
plots <- list(...)
g <- ggplotGrob(plots[[1]] + theme(legend.position="bottom"))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
lheight <- sum(legend$height)
grid.arrange(
do.call(arrangeGrob, lapply(plots, function(x)
x + theme(legend.position="none"))),
legend,
ncol = 1,
heights = unit.c(unit(1, "npc") - lheight, lheight))
}
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
p1 <- qplot(carat, price, data=dsamp, colour=clarity)
p2 <- qplot(cut, price, data=dsamp, colour=clarity)
p3 <- qplot(color, price, data=dsamp, colour=clarity)
p4 <- qplot(depth, price, data=dsamp, colour=clarity)
grid_arrange_shared_legend(p1, p2, p3, p4)
Note the lack of ggplot_gtable
and ggplot_build
. ggplotGrob
is used instead. This example is a bit more convoluted than the above solution but it still solved it for me.
check your cpanels space.remove unused file or error.log file & then try to login your application(This work for me);
I had a similiar problem and the only solution was rebooting vagrant which I use as dev enviroment. Beside that, not a single artisan and composer command didn't help.
Unfortunately to be able to use the extension modules provided by others you'll be forced to use the official compiler to compile Python. These are:
Visual Studio 2008 for Python 2.7. See: https://docs.python.org/2.7/using/windows.html#compiling-python-on-windows
Visual Studio 2010 for Python 3.4. See: https://docs.python.org/3.4/using/windows.html#compiling-python-on-windows
Alternatively, you can use MinGw to compile extensions in a way that won't depend on others.
See: https://docs.python.org/2/install/#gnu-c-cygwin-MinGW or https://docs.python.org/3.4/install/#gnu-c-cygwin-mingw
This allows you to have one compiler to build your extensions for both versions of Python, Python 2.x and Python 3.x.
Here's how you can mock your FileConnection
Mock<IFileConnection> fileConnection = new Mock<IFileConnection>(
MockBehavior.Strict);
fileConnection.Setup(item => item.Get(It.IsAny<string>,It.IsAny<string>))
.Throws(new IOException());
Then instantiate your Transfer class and use the mock in your method call
Transfer transfer = new Transfer();
transfer.GetFile(fileConnection.Object, someRemoteFilename, someLocalFileName);
Update:
First of all you have to mock your dependencies only, not the class you are testing(Transfer class in this case). Stating those dependencies in your constructor make it easy to see what services your class needs to work. It also makes it possible to replace them with fakes when you are writing your unit tests. At the moment it's impossible to replace those properties with fakes.
Since you are setting those properties using another dependency, I would write it like this:
public class Transfer
{
public Transfer(IInternalConfig internalConfig)
{
source = internalConfig.GetFileConnection("source");
destination = internalConfig.GetFileConnection("destination");
}
//you should consider making these private or protected fields
public virtual IFileConnection source { get; set; }
public virtual IFileConnection destination { get; set; }
public virtual void GetFile(IFileConnection connection,
string remoteFilename, string localFilename)
{
connection.Get(remoteFilename, localFilename);
}
public virtual void PutFile(IFileConnection connection,
string localFilename, string remoteFilename)
{
connection.Get(remoteFilename, localFilename);
}
public virtual void TransferFiles(string sourceName, string destName)
{
var tempName = Path.GetTempFileName();
GetFile(source, sourceName, tempName);
PutFile(destination, tempName, destName);
}
}
This way you can mock internalConfig and make it return IFileConnection mocks that does what you want.
For generate random string, you can use:
SUBSTRING(MD5(RAND()) FROM 1 FOR 8)
You recieve smth like that:
353E50CC
To convert an integer to a string also involves char
array or memory management.
To handle that part for such short arrays, code could use a compound literal, since C99, to create array space, on the fly. The string is valid until the end of the block.
#define UNS_HEX_STR_SIZE ((sizeof (unsigned)*CHAR_BIT + 3)/4 + 1)
// compound literal v--------------------------v
#define U2HS(x) unsigned_to_hex_string((x), (char[UNS_HEX_STR_SIZE]) {0}, UNS_HEX_STR_SIZE)
char *unsigned_to_hex_string(unsigned x, char *dest, size_t size) {
snprintf(dest, size, "%X", x);
return dest;
}
int main(void) {
// 3 array are formed v v v
printf("%s %s %s\n", U2HS(UINT_MAX), U2HS(0), U2HS(0x12345678));
char *hs = U2HS(rand());
puts(hs);
// `hs` is valid until the end of the block
}
Output
FFFFFFFF 0 12345678
5851F42D
There are two steps to fix this.
First edit phpMyAdmin/libraries/DatabaseInterface.class.php
Change:
if (PMA_MYSQL_INT_VERSION > 50503) {
$default_charset = 'utf8mb4';
$default_collation = 'utf8mb4_general_ci';
} else {
$default_charset = 'utf8';
$default_collation = 'utf8_general_ci';
}
To:
//if (PMA_MYSQL_INT_VERSION > 50503) {
// $default_charset = 'utf8mb4';
// $default_collation = 'utf8mb4_general_ci';
//} else {
$default_charset = 'utf8';
$default_collation = 'utf8_general_ci';
//}
Then delete this cookie from your browser "pma_collation_connection".
Or delete all Cookies.
Then restart your phpMyAdmin.
(It would be nice if phpMyAdmin allowed you to set the charset and collation per server in the config.inc.php)
DANGER AHEAD: (please read the comments. Executing the command proposed in my answer might delete more than you want)
to completely remove all files including directories I had to run
git clean -f -d
According to C99 standard, section 6.5.5 Multiplicative operators, the following is required:
(a / b) * b + a % b = a
The sign of the result of a remainder operation, according to C99, is the same as the dividend's one.
Let's see some examples (dividend / divisor
):
(-3 / 2) * 2 + -3 % 2 = -3
(-3 / 2) * 2 = -2
(-3 % 2) must be -1
(3 / -2) * -2 + 3 % -2 = 3
(3 / -2) * -2 = 2
(3 % -2) must be 1
(-3 / -2) * -2 + -3 % -2 = -3
(-3 / -2) * -2 = -2
(-3 % -2) must be -1
6.5.5 Multiplicative operators
Syntax
- multiplicative-expression:
cast-expression
multiplicative-expression * cast-expression
multiplicative-expression / cast-expression
multiplicative-expression % cast-expression
Constraints
- Each of the operands shall have arithmetic type. The operands of the % operator shall have integer type.
Semantics
The usual arithmetic conversions are performed on the operands.
The result of the binary * operator is the product of the operands.
The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.
When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded [1]. If the quotient
a/b
is representable, the expression(a/b)*b + a%b
shall equala
.[1]: This is often called "truncation toward zero".
I can run on my device at last, just I enabled the "USB debugging" and "Allow mock location" options from the Debug Menu of my device.
If you can generate the Excel file on the server, that is probably the best way. With Excel you can add formatting and get the output to look better. Several Excel options have already been mentioned. If you have a PHP backend, you might consider phpExcel.
If you are trying to do everything on the client in javascript, I don't think Excel is an option. You could create a CSV file and create a data URL to allow the user to download it.
I created a JSFiddle to demonstrate: http://jsfiddle.net/5KRf6/3/
This javascript (assuming you are using jQuery) will take the values out of input boxes in a table and build a CSV formatted string:
var csv = "";
$("table").find("tr").each(function () {
var sep = "";
$(this).find("input").each(function () {
csv += sep + $(this).val();
sep = ",";
});
csv += "\n";
});
If you wish, you can drop the data into a tag on the page (in my case a tag with an id of "csv"):
$("#csv").text(csv);
You can generate a URL to that text with this code:
window.URL = window.URL || window.webkiURL;
var blob = new Blob([csv]);
var blobURL = window.URL.createObjectURL(blob);
Finally, this will add a link to download that data:
$("#downloadLink").html("");
$("<a></a>").
attr("href", blobURL).
attr("download", "data.csv").
text("Download Data").
appendTo('#downloadLink');
Array.Equals() appears to only test for the same instance.
There doesn't appear to be a method that compares the values but it would be very easy to write.
Just compare the lengths, if not equal, return false. Otherwise, loop through each value in the array and determine if they match.
Here are simple regex to understand (verified, and no preceding 0)
Between 0 to 100 (Try it here):
^(0|[1-9][0-9]?|100)$
Between 1 to 100 (Try it here):
^([1-9][0-9]?|100)$
you can use cURL library for posting data: http://www.php.net/curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL, "http://websiteURL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "XML=".$xmlcontent."&password=".$password."&etc=etc");
$content=curl_exec($ch);
where postfield contains XML you need to send - you will need to name the postfield the API service (Clickatell I guess) expects
Cleanest way is to do it step by step. Use an each funciton to itterate through each element. As soon as that element is appended, pass it to a subsequent function to process that element.
function processAppended(el){
//process appended element
}
var remove = '<a href="#">remove</a>' ;
$('li').each(function(){
$(this).append(remove);
processAppended(this);
});?
This command installs npm package username/package
from specific git commit:
npm install https://github.com/username/package#3d0a21cc
Here 3d0a21cc
is first 8 characters of commit hash.
If you can't follow Max's suggestion of installing Blat (or any other utility) on your server, then perhaps your server already has software installed that can send emails.
I know that both Oracle and SqlServer have the capability to send email. You might have to work with your DBA to get that feature enabled and/or get the privilege to use it. Of course I can see how that might present its own set of problems and red tape. Assuming you can access the feature, it is fairly simple to have a batch file login to a database and send mail.
A batch file can easily run a VBScript via CSCRIPT. A quick google search finds many links showing how to send email with VBScript. The first one I happened to look at was http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/enterprise/mail/. It looks straight forward.
In Windows 7, make sure Event Viewer closed before deleting.