The best way is probably to use:
:%s/phrase//gc
c
asks for confirmation before each deletion. g
allows multiple replacements to occur on the same line.
You can also just search using /phrase
, select the next match with gn
, and delete it with d
.
How about something like: Using HTML Agility Pack
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(@"<html><body><p><table id=""foo""><tr><th>hello</th></tr><tr><td>world</td></tr></table></body></html>");
foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table")) {
Console.WriteLine("Found: " + table.Id);
foreach (HtmlNode row in table.SelectNodes("tr")) {
Console.WriteLine("row");
foreach (HtmlNode cell in row.SelectNodes("th|td")) {
Console.WriteLine("cell: " + cell.InnerText);
}
}
}
Note that you can make it prettier with LINQ-to-Objects if you want:
var query = from table in doc.DocumentNode.SelectNodes("//table").Cast<HtmlNode>()
from row in table.SelectNodes("tr").Cast<HtmlNode>()
from cell in row.SelectNodes("th|td").Cast<HtmlNode>()
select new {Table = table.Id, CellText = cell.InnerText};
foreach(var cell in query) {
Console.WriteLine("{0}: {1}", cell.Table, cell.CellText);
}
Using strings for concatenation can lead to a runtime complexity on the order of O(n^2)
.
If you use a StringBuilder
, there is a lot less copying of memory that has to be done. With the StringBuilder(int capacity)
you can increase performance if you can estimate how large the final String
is going to be. Even if you're not precise, you'll probably only have to grow the capacity of StringBuilder
a couple of times which can help performance also.
Maybe you are not allowed to start the service "MySQL 55". Set the login information of Service "MySQL 55" as local!
To see the list of aviable services in Windows 7:
services.msc
and press return.MySQL55
In addition to the above mentioned answers: I wanted to start a job with a simple parameter passed to a second pipeline and found the answer on http://web.archive.org/web/20160209062101/https://dzone.com/refcardz/continuous-delivery-with-jenkins-workflow
So i used:
stage ('Starting ART job') {
build job: 'RunArtInTest', parameters: [[$class: 'StringParameterValue', name: 'systemname', value: systemname]]
}
Building off of deepee1 and this, here's how to accept a class name in a string, and then use it to read and write to a database with LINQ. I use "dynamic" instead of deepee1's casting because it allows me to assign properties, which allows us to dynamically select and operate on any table we want.
Type tableType = Assembly.GetExecutingAssembly().GetType("NameSpace.TableName");
ITable itable = dbcontext.GetTable(tableType);
//prints contents of the table
foreach (object y in itable) {
string value = (string)y.GetType().GetProperty("ColumnName").GetValue(y, null);
Console.WriteLine(value);
}
//inserting into a table
dynamic tableClass = Activator.CreateInstance(tableType);
//Alternative to using tableType, using Tony's tips
dynamic tableClass = Activator.CreateInstance(null, "NameSpace.TableName").Unwrap();
tableClass.Word = userParameter;
itable.InsertOnSubmit(tableClass);
dbcontext.SubmitChanges();
//sql equivalent
dbcontext.ExecuteCommand("INSERT INTO [TableNme]([ColumnName]) VALUES ({0})", userParameter);
Use org.junit.Assert's method assertArrayEquals
:
import org.junit.Assert;
...
Assert.assertArrayEquals( expectedResult, result );
If this method is not available, you may have accidentally imported the Assert class from junit.framework
.
Try the following to support basic html tags including ul ol li tags. Create a Tag handler as shown below
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.Html.TagHandler;
import android.util.Log;
public class MyTagHandler implements TagHandler {
boolean first= true;
String parent=null;
int index=1;
@Override
public void handleTag(boolean opening, String tag, Editable output,
XMLReader xmlReader) {
if(tag.equals("ul")) parent="ul";
else if(tag.equals("ol")) parent="ol";
if(tag.equals("li")){
if(parent.equals("ul")){
if(first){
output.append("\n\t•");
first= false;
}else{
first = true;
}
}
else{
if(first){
output.append("\n\t"+index+". ");
first= false;
index++;
}else{
first = true;
}
}
}
}
}
Set the text on Activity as shown below
@SuppressWarnings("deprecation")
public void init(){
try {
TextView help = (TextView) findViewById(R.id.help);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
help.setText(Html.fromHtml(getString(R.string.help_html),Html.FROM_HTML_MODE_LEGACY, null, new MyTagHandler()));
} else {
help.setText(Html.fromHtml(getString(R.string.help_html), null, new MyTagHandler()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
And html text on resource string files as
<![CDATA[ ...raw html data ...]] >
Like Yuck's answer with a check to allow the script to be ran more than once without error. (less code/custom strings than using information_schema.columns)
IF object_id('DF_SomeName', 'D') IS NULL BEGIN
Print 'Creating Constraint DF_SomeName'
ALTER TABLE Employee ADD CONSTRAINT DF_SomeName DEFAULT N'SANDNES' FOR CityBorn;
END
public static void main(String[] args) throws InterruptedException {
//type code
short z=1000;
Thread.sleep(z);/*will provide 1 second delay. alter data type of z or value of z for longer delays required */
//type code
}
eg:-
class TypeCasting {
public static void main(String[] args) throws InterruptedException {
short f = 1;
int a = 123687889;
short b = 2;
long c = 4567;
long d=45;
short z=1000;
System.out.println("Value of a,b and c are\n" + a + "\n" + b + "\n" + c + "respectively");
c = a;
b = (short) c;
System.out.println("Typecasting...........");
Thread.sleep(z);
System.out.println("Value of B after Typecasting" + b);
System.out.println("Value of A is" + a);
}
}
I think the best library is : https://github.com/chrisbanes/Android-PullToRefresh.
Works with:
ListView
ExpandableListView
GridView
WebView
ScrollView
HorizontalScrollView
ViewPager
In PHP and C++ you can use the printf() function
printf("$%01.2f", $money);
Check Calendar
class. It has add
method (and some others) to allow time manipulation.
Something like this should work:
Calendar cal = Calendar.getInstance(); // creates calendar
cal.setTime(new Date()); // sets calendar time/date
cal.add(Calendar.HOUR_OF_DAY, 1); // adds one hour
cal.getTime(); // returns new date object plus one hour
Check API for more.
To simplify: Only configuration files can access environment variables - and then pass them on.
Step 1.) Add your variable to your .env
file, for example,
EXAMPLE_URL="http://google.com"
Step 2.) Create a new file inside of the config
folder, with any name, for example,
config/example.php
Step 3.) Inside of this new file, I add an array being returned, containing that environment variable.
<?php
return [
'url' => env('EXAMPLE_URL')
];
Step 4.) Because I named it "example", my configuration 'namespace' is now example. So now, in my controller I can access this variable with:
$url = \config('example.url');
Tip - if you add use Config;
at the top of your controller, you don't need the backslash (which designates the root namespace). For example,
namespace App\Http\Controllers;
use Config; // Added this line
class ExampleController extends Controller
{
public function url() {
return config('example.url');
}
}
Finally, commit the changes:
php artisan config:cache
--- IMPORTANT --- Remember to enter php artisan config:cache
into the console once you have created your example.php file. Configuration files and variables are cached, so if you make changes you need to flush that cache - the same applies to the .env
file being changed / added to.
Once you set your Global Jenkins credentials, you can apply this step:
stage('Update GIT') {
steps {
script {
catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
withCredentials([usernamePassword(credentialsId: 'example-secure', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
def encodedPassword = URLEncoder.encode("$GIT_PASSWORD",'UTF-8')
sh "git config user.email [email protected]"
sh "git config user.name example"
sh "git add ."
sh "git commit -m 'Triggered Build: ${env.BUILD_NUMBER}'"
sh "git push https://${GIT_USERNAME}:${encodedPassword}@github.com/${GIT_USERNAME}/example.git"
}
}
}
}
}
I had a simular issue and resolved it using android:adjustViewBounds="true"
on the ImageView.
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:contentDescription="@string/banner_alt"
android:src="@drawable/banner_portrait" />
I've got this one, which sets a cookie. And as you can see, it first checks if the language is posted by the user. Because browser language not always tells about the user.
<?php
$lang = getenv("HTTP_ACCEPT_LANGUAGE");
$set_lang = explode(',', $lang);
if (isset($_POST['lang']))
{
$taal = $_POST['lang'];
setcookie("lang", $taal);
header('Location: /p/');
}
else
{
setcookie("lang", $set_lang[0]);
echo $set_lang[0];
echo '<br>';
echo $set_lang[1];
header('Location: /p/');
}
?>
var result = from entry in table
where entry.something.Equals(null)
select entry;
MSDN Reference: LINQ to SQL: .NET Language-Integrated Query for Relational Data
Delete the following information related to signing certificate in the certificate store
<PropertyGroup>
<ManifestCertificateThumbprint>xxxxx xxxxxx</ManifestCertificateThumbprint>
<ManifestKeyFile>xxxxxxxx.pfx</ManifestKeyFile>
<GenerateManifests>true</GenerateManifests>
<SignManifests>false</SignManifests>
</PropertyGroup>
It happens when you don't properly close the code block:
if (condition){
// your code goes here*
{ // This doesn't close the code block
Correct way:
if (condition){
// your code goes here
} // Close the code block
You can simply import the data from the source file, read it, and save what you want to append to a variable. Then open the destination file, assign the list data inside to a new variable (presumably this will all be valid JSON), then use the 'append' function on this list variable and append the first variable to it. Viola, you have appended to the JSON list. Now just overwrite your destination file with the newly appended list (as JSON).
The 'a' mode in your 'open' function will not work here because it will just tack everything on to the end of the file, which will make it non-valid JSON format.
Specify the keyword args linestyle
and/or marker
in your call to plot
.
For example, using a dashed line and blue circle markers:
plt.plot(range(10), linestyle='--', marker='o', color='b')
A shortcut call for the same thing:
plt.plot(range(10), '--bo')
Here is a list of the possible line and marker styles:
================ ===============================
character description
================ ===============================
- solid line style
-- dashed line style
-. dash-dot line style
: dotted line style
. point marker
, pixel marker
o circle marker
v triangle_down marker
^ triangle_up marker
< triangle_left marker
> triangle_right marker
1 tri_down marker
2 tri_up marker
3 tri_left marker
4 tri_right marker
s square marker
p pentagon marker
* star marker
h hexagon1 marker
H hexagon2 marker
+ plus marker
x x marker
D diamond marker
d thin_diamond marker
| vline marker
_ hline marker
================ ===============================
edit: with an example of marking an arbitrary subset of points, as requested in the comments:
import numpy as np
import matplotlib.pyplot as plt
xs = np.linspace(-np.pi, np.pi, 30)
ys = np.sin(xs)
markers_on = [12, 17, 18, 19]
plt.plot(xs, ys, '-gD', markevery=markers_on)
plt.show()
This last example using the markevery
kwarg is possible in since 1.4+, due to the merge of this feature branch. If you are stuck on an older version of matplotlib, you can still achieve the result by overlaying a scatterplot on the line plot. See the edit history for more details.
In AWS LAMBDA:
For $ sam local
you add the following line in your sam template yml file:
Resources:
FunctionName:
Properties:
Environment:
Variables:
SPRING_PROFILES_ACTIVE: local
But in AWS Console: in your Lambda Environment variables just add:
KEY:JAVA_TOOL_OPTIONS
VALUE:-Dspring.profiles.active=dev
No point repeating the other answers, but please note that strdup()
can do anything it wants from a C perspective, since it is not part of any C standard. It is however defined by POSIX.1-2001.
Try setting a default value in the css (to let it know where you want it to start out)
position: relative;
transition: all 2s ease 0s;
top: 0; /* start out at position 0 */
I found this solution useful in a NodeJS app. I use it just in desperate cases because it launches a timeout in order to wait for the full page load.
The second argument is the callback function which is going to be called once the response is ready.
phantom = require('phantom');
var fullLoad = function(anUrl, callbackDone) {
phantom.create(function (ph) {
ph.createPage(function (page) {
page.open(anUrl, function (status) {
if (status !== 'success') {
console.error("pahtom: error opening " + anUrl, status);
ph.exit();
} else {
// timeOut
global.setTimeout(function () {
page.evaluate(function () {
return document.documentElement.innerHTML;
}, function (result) {
ph.exit(); // EXTREMLY IMPORTANT
callbackDone(result); // callback
});
}, 5000);
}
});
});
});
}
var callback = function(htmlBody) {
// do smth with the htmlBody
}
fullLoad('your/url/', callback);
As of today I still find the Ahead-of-Time Compilation cookbook as the best recipe for production bundling. You can find it here: https://angular.io/docs/ts/latest/cookbook/aot-compiler.html
My experience with Angular 2 so far is that AoT creates the smallest builds with almost no loading time. And most important as the question here is about - you only need to ship a few files to production.
This seems to be because the Angular compiler will not be shipped with the production builds as the templates are compiled "Ahead of Time". It's also very cool to see your HTML template markup transformed to javascript instructions that would be very hard to reverse engineer into the original HTML.
I've made a simple video where I demonstrate download size, number of files etc. for an Angular 2 app in dev vs AoT build - which you can see here:
You'll find the source code used in the video here:
In addition to AIXroot's answer, there is also a logout function that can be used to write a utmp logout record. So if you don't have any processes for user xxxx, but userdel says "userdel: account xxxx is currently in use", you can add a logout record manually. Create a file logout.c like this:
#include <stdio.h>
#include <utmp.h>
int main(int argc, char *argv[])
{
if (argc == 2) {
return logout(argv[1]);
}
else {
fprintf(stderr, "Usage: logout device\n");
return 1;
}
}
Compile it:
gcc -lutil -o logout logout.c
And then run it for whatever it says in the output of finger's "On since" line(s) as a parameter:
# finger xxxx
Login: xxxx Name:
Directory: /home/xxxx Shell: /bin/bash
On since Sun Feb 26 11:06 (GMT) on 127.0.0.1:6 (messages off) from 127.0.0.1
On since Fri Feb 24 16:53 (GMT) on pts/6, idle 3 days 17:16, from 127.0.0.1
Last login Mon Feb 10 14:45 (GMT) on pts/11 from somehost.example.com
Mail last read Sun Feb 27 08:44 2014 (GMT)
No Plan.
# userdel xxxx
userdel: account `xxxx' is currently in use.
# ./logout 127.0.0.1:6
# ./logout pts/6
# userdel xxxx
no crontab for xxxx
I tried the following and it worked from my local file system.. Basically spark can read from local, HDFS and AWS S3 path
listrdd=sc.textFile("file:////home/cloudera/Downloads/master-data/retail_db/products")
This popup shows only when you get a fatal exception in your code which stops the execution of the app. It could be any exception NullPointerException
, OutOfMemoryException
etc.
Best way to check is through Logcat if you are still developing the app in Android studio which is quick way to read stack trace and check the cause of the app.
If your app is already live, then you can not use logcat. So, for that you can implement Crashlytics
to provide you bug reports of any exception that occurs.
Believe it or not, this is normal behaviour. An exception is thrown but handled by the XmlSerializer, so if you just ignore it everything should continue on fine.
I have found this very annoying, and there have been many complaints about this if you search around a bit, but from what I've read Microsoft don't plan on doing anything about it.
You can avoid getting Exception popups all the time while debugging if you switch off first chance exceptions for that specific exception. In Visual Studio, go to Debug -> Exceptions (or press Ctrl + Alt + E), Common Language Runtime Exceptions -> System.IO -> System.IO.FileNotFoundException.
You can find information about another way around it in the blog post C# XmlSerializer FileNotFound exception (which discusses Chris Sells' tool XmlSerializerPreCompiler).
Some (outdated) guidelines say so, such as MISRA C:
The requirement for a final default clause is defensive programming. This clause shall either take appropriate action or contain a suitable comment as to why no action is taken.
That advice is outdated because it is not based on currently relevant criteria. The glaring omission being what Harlan Kassler said:
Leaving out the default case enables the compiler to optionally warn or fail when it sees an unhandled case. Static verifiability is after all better than any dynamic check, and therefore not a worthy sacrifice for when you need the dynamic check as well.
As Harlan also demonstrated, the functional equivalent of a default case can be recreated after the switch. Which is trivial when each case is an early return.
The typical need for a dynamic check is input handling, in a wide sense. If a value comes from outside the program's control, it can't be trusted.
This is also where Misra takes the standpoint of extreme defensive programming, whereby as long as an invalid value is physically representable, it must be checked for, no matter if the program is provably correct. Which makes sense if the software needs to be as reliable as possible in the presence of hardware errors. But as Ophir Yoktan said, most software are better off not "handling" bugs. The latter practice is sometimes called offensive programming.
I think you are not configured properly,
if you are using XAMPP then you can easily send mail from localhost.
for example you can configure C:\xampp\php\php.ini
and c:\xampp\sendmail\sendmail.ini
for gmail to send mail.
in C:\xampp\php\php.ini
find extension=php_openssl.dll
and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.
in php.ini file find [mail function]
and change
SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"
(use the above send mail path only and it will work)
Now Open C:\xampp\sendmail\sendmail.ini
. Replace all the existing code in sendmail.ini with following code
[sendmail]
smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]
Now you have done!! create php file with mail function and send mail from localhost.
Update
First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()
).
You can set the following settings in your PHP.ini:
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
That also happened to me on a recreated directory, the directory is the same but to make it work again just run:
cd .
Create a function script that is called earlier than all other functions without passing any arguments to it, like this:
! /bin/bash
function init(){ ORIGOPT= "- $@ -" }
Afer that, you can call init and use the ORIGOPT var as needed,as a plus, I always assign a new var and copy the contents of ORIGOPT in my new functions, that way you can keep yourself assured nobody is going to touch it or change it.
I added spaces and dashes to make it easier to parse it with 'sed -E' also bash will not pass it as reference and make ORIGOPT grow as functions are called with more arguments.
Q:Can't bind to 'pSelectableRow' since it isn't a known property of 'tr'.
A:you need to configure the primeng tabulemodule in ngmodule
AFAIK, the only way this could be done is by using the state=directory
option.
While template
module supports most of copy
options, which in turn supports most file
options, you can not use something like state=directory
with it. Moreover, it would be quite confusing (would it mean that {{project_root}}/conf/code.conf
is a directory ? or would it mean that {{project_root}}/conf/
should be created first.
So I don't think this is possible right now without adding a previous file
task.
- file:
path: "{{project_root}}/conf"
state: directory
recurse: yes
As hinted in this question, you have to "open" the lower-level artist API, by storing the figure and axis objects passed by the matplotlib functions you call (the fig
, ax
and cax
variables below). You can then replace the default x- and y-axis ticks using set_xticklabels
/set_yticklabels
:
from sklearn.metrics import confusion_matrix
labels = ['business', 'health']
cm = confusion_matrix(y_test, pred, labels)
print(cm)
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(cm)
plt.title('Confusion matrix of the classifier')
fig.colorbar(cax)
ax.set_xticklabels([''] + labels)
ax.set_yticklabels([''] + labels)
plt.xlabel('Predicted')
plt.ylabel('True')
plt.show()
Note that I passed the labels
list to the confusion_matrix
function to make sure it's properly sorted, matching the ticks.
This results in the following figure:
You can generate pairs like this:
{(x, x + 2) for x in r if x + 2 in r}
Then all that is left to do is to get a condition to make them prime, which you have already done in the first example.
A different way of doing it: (Although slower for large sets of primes)
{(x, y) for x in r for y in r if x + 2 == y}
boost:ptr_array
http://www.boost.org/doc/libs/1_43_0/libs/ptr_container/doc/ptr_array.html
I've built upon the answer above - https://stackoverflow.com/a/11155031/2060486 - to create a shadow around ALL sides..
private static final int GRAY_COLOR_FOR_SHADE = Color.argb(50, 79, 79, 79);
// this method takes a bitmap and draws around it 4 rectangles with gradient to create a
// shadow effect.
public static Bitmap addShadowToBitmap(Bitmap origBitmap) {
int shadowThickness = 13; // can be adjusted as needed
int bmpOriginalWidth = origBitmap.getWidth();
int bmpOriginalHeight = origBitmap.getHeight();
int bigW = bmpOriginalWidth + shadowThickness * 2; // getting dimensions for a bigger bitmap with margins
int bigH = bmpOriginalHeight + shadowThickness * 2;
Bitmap containerBitmap = Bitmap.createBitmap(bigW, bigH, Bitmap.Config.ARGB_8888);
Bitmap copyOfOrigBitmap = Bitmap.createScaledBitmap(origBitmap, bmpOriginalWidth, bmpOriginalHeight, false);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
Canvas canvas = new Canvas(containerBitmap); // drawing the shades on the bigger bitmap
//right shade - direction of gradient is positive x (width)
Shader rightShader = new LinearGradient(bmpOriginalWidth, 0, bigW, 0, GRAY_COLOR_FOR_SHADE,
Color.TRANSPARENT, Shader.TileMode.CLAMP);
paint.setShader(rightShader);
canvas.drawRect(bigW - shadowThickness, shadowThickness, bigW, bigH - shadowThickness, paint);
//bottom shade - direction is positive y (height)
Shader bottomShader = new LinearGradient(0, bmpOriginalHeight, 0, bigH, GRAY_COLOR_FOR_SHADE,
Color.TRANSPARENT, Shader.TileMode.CLAMP);
paint.setShader(bottomShader);
canvas.drawRect(shadowThickness, bigH - shadowThickness, bigW - shadowThickness, bigH, paint);
//left shade - direction is negative x
Shader leftShader = new LinearGradient(shadowThickness, 0, 0, 0, GRAY_COLOR_FOR_SHADE,
Color.TRANSPARENT, Shader.TileMode.CLAMP);
paint.setShader(leftShader);
canvas.drawRect(0, shadowThickness, shadowThickness, bigH - shadowThickness, paint);
//top shade - direction is negative y
Shader topShader = new LinearGradient(0, shadowThickness, 0, 0, GRAY_COLOR_FOR_SHADE,
Color.TRANSPARENT, Shader.TileMode.CLAMP);
paint.setShader(topShader);
canvas.drawRect(shadowThickness, 0, bigW - shadowThickness, shadowThickness, paint);
// starting to draw bitmap not from 0,0 to get margins for shade rectangles
canvas.drawBitmap(copyOfOrigBitmap, shadowThickness, shadowThickness, null);
return containerBitmap;
}
Change the color in the const as you see fit.
Go to Tools|options|keymap. Search for 'zoom in text' and set your preferred key. I've set alt+plus and alt+minus.
@amitchhajer 's post works for GNU tar. If someone finds this post and needs it to work on a NON GNU
system, they can do this:
tar cvf - folderToCompress | gzip > compressFileName
To expand the archive:
zcat compressFileName | tar xvf -
The problem is that the timer
variable is local, and its value is lost after each function call.
You need to persist it, you can put it outside the function, or if you don't want to expose the variable as global, you can store it in a closure, e.g.:
var endAndStartTimer = (function () {
var timer; // variable persisted here
return function () {
window.clearTimeout(timer);
//var millisecBeforeRedirect = 10000;
timer = window.setTimeout(function(){alert('Hello!');},10000);
};
})();
I tried the answers here in a giant for...if loop, but didn't get any joy - so I did it like this, maybe messy but did the job:
# EXP_LIST2 is iterated
# imagine a for loop
EXP_LIST="List item"
EXP_LIST2="$EXP_LIST2 \n $EXP_LIST"
done
echo -e $EXP_LIST2
although that added a space to the list, which is fine - I wanted it indented a bit. Also presume the "\n" could be printed in the original $EP_LIST.
Split creates an array . You can access the individual values by using a index.
var result=$(row).val().split('|')[2]
alert(result);
OR
var result=$(row).val().split('|');
alert(result[2]);
If it's input element then you need to use $(row).val()
to get the value..
Otherwise you would need to use $(row).text()
or $(row).html()
Slow, ugly, platform-specific... but one-liner ;-)
import subprocess
contents = subprocess.Popen('cat %s' % filename, shell = True, stdout = subprocess.PIPE).communicate()[0]
var a = ["a","a","b","c","c"];
a.filter(function(value,index,self){ return (self.indexOf(value) !== index )})
Here is the MD5 code inserted in an Excel Module with the name "module_md5":
Private Const BITS_TO_A_BYTE = 8
Private Const BYTES_TO_A_WORD = 4
Private Const BITS_TO_A_WORD = 32
Private m_lOnBits(30)
Private m_l2Power(30)
Sub SetUpArrays()
m_lOnBits(0) = CLng(1)
m_lOnBits(1) = CLng(3)
m_lOnBits(2) = CLng(7)
m_lOnBits(3) = CLng(15)
m_lOnBits(4) = CLng(31)
m_lOnBits(5) = CLng(63)
m_lOnBits(6) = CLng(127)
m_lOnBits(7) = CLng(255)
m_lOnBits(8) = CLng(511)
m_lOnBits(9) = CLng(1023)
m_lOnBits(10) = CLng(2047)
m_lOnBits(11) = CLng(4095)
m_lOnBits(12) = CLng(8191)
m_lOnBits(13) = CLng(16383)
m_lOnBits(14) = CLng(32767)
m_lOnBits(15) = CLng(65535)
m_lOnBits(16) = CLng(131071)
m_lOnBits(17) = CLng(262143)
m_lOnBits(18) = CLng(524287)
m_lOnBits(19) = CLng(1048575)
m_lOnBits(20) = CLng(2097151)
m_lOnBits(21) = CLng(4194303)
m_lOnBits(22) = CLng(8388607)
m_lOnBits(23) = CLng(16777215)
m_lOnBits(24) = CLng(33554431)
m_lOnBits(25) = CLng(67108863)
m_lOnBits(26) = CLng(134217727)
m_lOnBits(27) = CLng(268435455)
m_lOnBits(28) = CLng(536870911)
m_lOnBits(29) = CLng(1073741823)
m_lOnBits(30) = CLng(2147483647)
m_l2Power(0) = CLng(1)
m_l2Power(1) = CLng(2)
m_l2Power(2) = CLng(4)
m_l2Power(3) = CLng(8)
m_l2Power(4) = CLng(16)
m_l2Power(5) = CLng(32)
m_l2Power(6) = CLng(64)
m_l2Power(7) = CLng(128)
m_l2Power(8) = CLng(256)
m_l2Power(9) = CLng(512)
m_l2Power(10) = CLng(1024)
m_l2Power(11) = CLng(2048)
m_l2Power(12) = CLng(4096)
m_l2Power(13) = CLng(8192)
m_l2Power(14) = CLng(16384)
m_l2Power(15) = CLng(32768)
m_l2Power(16) = CLng(65536)
m_l2Power(17) = CLng(131072)
m_l2Power(18) = CLng(262144)
m_l2Power(19) = CLng(524288)
m_l2Power(20) = CLng(1048576)
m_l2Power(21) = CLng(2097152)
m_l2Power(22) = CLng(4194304)
m_l2Power(23) = CLng(8388608)
m_l2Power(24) = CLng(16777216)
m_l2Power(25) = CLng(33554432)
m_l2Power(26) = CLng(67108864)
m_l2Power(27) = CLng(134217728)
m_l2Power(28) = CLng(268435456)
m_l2Power(29) = CLng(536870912)
m_l2Power(30) = CLng(1073741824)
End Sub
Private Function LShift(lValue, iShiftBits)
If iShiftBits = 0 Then
LShift = lValue
Exit Function
ElseIf iShiftBits = 31 Then
If lValue And 1 Then
LShift = &H80000000
Else
LShift = 0
End If
Exit Function
ElseIf iShiftBits < 0 Or iShiftBits > 31 Then
Err.Raise 6
End If
If (lValue And m_l2Power(31 - iShiftBits)) Then
LShift = ((lValue And m_lOnBits(31 - (iShiftBits + 1))) * m_l2Power(iShiftBits)) Or &H80000000
Else
LShift = ((lValue And m_lOnBits(31 - iShiftBits)) * m_l2Power(iShiftBits))
End If
End Function
Private Function RShift(lValue, iShiftBits)
If iShiftBits = 0 Then
RShift = lValue
Exit Function
ElseIf iShiftBits = 31 Then
If lValue And &H80000000 Then
RShift = 1
Else
RShift = 0
End If
Exit Function
ElseIf iShiftBits < 0 Or iShiftBits > 31 Then
Err.Raise 6
End If
RShift = (lValue And &H7FFFFFFE) \ m_l2Power(iShiftBits)
If (lValue And &H80000000) Then
RShift = (RShift Or (&H40000000 \ m_l2Power(iShiftBits - 1)))
End If
End Function
Private Function RotateLeft(lValue, iShiftBits)
RotateLeft = LShift(lValue, iShiftBits) Or RShift(lValue, (32 - iShiftBits))
End Function
Private Function AddUnsigned(lX, lY)
Dim lX4
Dim lY4
Dim lX8
Dim lY8
Dim lResult
lX8 = lX And &H80000000
lY8 = lY And &H80000000
lX4 = lX And &H40000000
lY4 = lY And &H40000000
lResult = (lX And &H3FFFFFFF) + (lY And &H3FFFFFFF)
If lX4 And lY4 Then
lResult = lResult Xor &H80000000 Xor lX8 Xor lY8
ElseIf lX4 Or lY4 Then
If lResult And &H40000000 Then
lResult = lResult Xor &HC0000000 Xor lX8 Xor lY8
Else
lResult = lResult Xor &H40000000 Xor lX8 Xor lY8
End If
Else
lResult = lResult Xor lX8 Xor lY8
End If
AddUnsigned = lResult
End Function
Private Function F(x, y, z)
F = (x And y) Or ((Not x) And z)
End Function
Private Function G(x, y, z)
G = (x And z) Or (y And (Not z))
End Function
Private Function H(x, y, z)
H = (x Xor y Xor z)
End Function
Private Function I(x, y, z)
I = (y Xor (x Or (Not z)))
End Function
Private Sub FF(a, b, c, d, x, s, ac)
a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac))
a = RotateLeft(a, s)
a = AddUnsigned(a, b)
End Sub
Private Sub GG(a, b, c, d, x, s, ac)
a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac))
a = RotateLeft(a, s)
a = AddUnsigned(a, b)
End Sub
Private Sub HH(a, b, c, d, x, s, ac)
a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac))
a = RotateLeft(a, s)
a = AddUnsigned(a, b)
End Sub
Private Sub II(a, b, c, d, x, s, ac)
a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac))
a = RotateLeft(a, s)
a = AddUnsigned(a, b)
End Sub
Private Function ConvertToWordArray(sMessage)
Dim lMessageLength
Dim lNumberOfWords
Dim lWordArray()
Dim lBytePosition
Dim lByteCount
Dim lWordCount
Const MODULUS_BITS = 512
Const CONGRUENT_BITS = 448
lMessageLength = Len(sMessage)
lNumberOfWords = (((lMessageLength + ((MODULUS_BITS - CONGRUENT_BITS) \ BITS_TO_A_BYTE)) \ (MODULUS_BITS \ BITS_TO_A_BYTE)) + 1) * (MODULUS_BITS \ BITS_TO_A_WORD)
ReDim lWordArray(lNumberOfWords - 1)
lBytePosition = 0
lByteCount = 0
Do Until lByteCount >= lMessageLength
lWordCount = lByteCount \ BYTES_TO_A_WORD
lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE
lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(Asc(Mid(sMessage, lByteCount + 1, 1)), lBytePosition)
lByteCount = lByteCount + 1
Loop
lWordCount = lByteCount \ BYTES_TO_A_WORD
lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE
lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(&H80, lBytePosition)
lWordArray(lNumberOfWords - 2) = LShift(lMessageLength, 3)
lWordArray(lNumberOfWords - 1) = RShift(lMessageLength, 29)
ConvertToWordArray = lWordArray
End Function
Private Function WordToHex(lValue)
Dim lByte
Dim lCount
For lCount = 0 To 3
lByte = RShift(lValue, lCount * BITS_TO_A_BYTE) And m_lOnBits(BITS_TO_A_BYTE - 1)
WordToHex = WordToHex & Right("0" & Hex(lByte), 2)
Next
End Function
Public Function MD5(sMessage)
module_md5.SetUpArrays
Dim x
Dim k
Dim AA
Dim BB
Dim CC
Dim DD
Dim a
Dim b
Dim c
Dim d
Const S11 = 7
Const S12 = 12
Const S13 = 17
Const S14 = 22
Const S21 = 5
Const S22 = 9
Const S23 = 14
Const S24 = 20
Const S31 = 4
Const S32 = 11
Const S33 = 16
Const S34 = 23
Const S41 = 6
Const S42 = 10
Const S43 = 15
Const S44 = 21
x = ConvertToWordArray(sMessage)
a = &H67452301
b = &HEFCDAB89
c = &H98BADCFE
d = &H10325476
For k = 0 To UBound(x) Step 16
AA = a
BB = b
CC = c
DD = d
FF a, b, c, d, x(k + 0), S11, &HD76AA478
FF d, a, b, c, x(k + 1), S12, &HE8C7B756
FF c, d, a, b, x(k + 2), S13, &H242070DB
FF b, c, d, a, x(k + 3), S14, &HC1BDCEEE
FF a, b, c, d, x(k + 4), S11, &HF57C0FAF
FF d, a, b, c, x(k + 5), S12, &H4787C62A
FF c, d, a, b, x(k + 6), S13, &HA8304613
FF b, c, d, a, x(k + 7), S14, &HFD469501
FF a, b, c, d, x(k + 8), S11, &H698098D8
FF d, a, b, c, x(k + 9), S12, &H8B44F7AF
FF c, d, a, b, x(k + 10), S13, &HFFFF5BB1
FF b, c, d, a, x(k + 11), S14, &H895CD7BE
FF a, b, c, d, x(k + 12), S11, &H6B901122
FF d, a, b, c, x(k + 13), S12, &HFD987193
FF c, d, a, b, x(k + 14), S13, &HA679438E
FF b, c, d, a, x(k + 15), S14, &H49B40821
GG a, b, c, d, x(k + 1), S21, &HF61E2562
GG d, a, b, c, x(k + 6), S22, &HC040B340
GG c, d, a, b, x(k + 11), S23, &H265E5A51
GG b, c, d, a, x(k + 0), S24, &HE9B6C7AA
GG a, b, c, d, x(k + 5), S21, &HD62F105D
GG d, a, b, c, x(k + 10), S22, &H2441453
GG c, d, a, b, x(k + 15), S23, &HD8A1E681
GG b, c, d, a, x(k + 4), S24, &HE7D3FBC8
GG a, b, c, d, x(k + 9), S21, &H21E1CDE6
GG d, a, b, c, x(k + 14), S22, &HC33707D6
GG c, d, a, b, x(k + 3), S23, &HF4D50D87
GG b, c, d, a, x(k + 8), S24, &H455A14ED
GG a, b, c, d, x(k + 13), S21, &HA9E3E905
GG d, a, b, c, x(k + 2), S22, &HFCEFA3F8
GG c, d, a, b, x(k + 7), S23, &H676F02D9
GG b, c, d, a, x(k + 12), S24, &H8D2A4C8A
HH a, b, c, d, x(k + 5), S31, &HFFFA3942
HH d, a, b, c, x(k + 8), S32, &H8771F681
HH c, d, a, b, x(k + 11), S33, &H6D9D6122
HH b, c, d, a, x(k + 14), S34, &HFDE5380C
HH a, b, c, d, x(k + 1), S31, &HA4BEEA44
HH d, a, b, c, x(k + 4), S32, &H4BDECFA9
HH c, d, a, b, x(k + 7), S33, &HF6BB4B60
HH b, c, d, a, x(k + 10), S34, &HBEBFBC70
HH a, b, c, d, x(k + 13), S31, &H289B7EC6
HH d, a, b, c, x(k + 0), S32, &HEAA127FA
HH c, d, a, b, x(k + 3), S33, &HD4EF3085
HH b, c, d, a, x(k + 6), S34, &H4881D05
HH a, b, c, d, x(k + 9), S31, &HD9D4D039
HH d, a, b, c, x(k + 12), S32, &HE6DB99E5
HH c, d, a, b, x(k + 15), S33, &H1FA27CF8
HH b, c, d, a, x(k + 2), S34, &HC4AC5665
II a, b, c, d, x(k + 0), S41, &HF4292244
II d, a, b, c, x(k + 7), S42, &H432AFF97
II c, d, a, b, x(k + 14), S43, &HAB9423A7
II b, c, d, a, x(k + 5), S44, &HFC93A039
II a, b, c, d, x(k + 12), S41, &H655B59C3
II d, a, b, c, x(k + 3), S42, &H8F0CCC92
II c, d, a, b, x(k + 10), S43, &HFFEFF47D
II b, c, d, a, x(k + 1), S44, &H85845DD1
II a, b, c, d, x(k + 8), S41, &H6FA87E4F
II d, a, b, c, x(k + 15), S42, &HFE2CE6E0
II c, d, a, b, x(k + 6), S43, &HA3014314
II b, c, d, a, x(k + 13), S44, &H4E0811A1
II a, b, c, d, x(k + 4), S41, &HF7537E82
II d, a, b, c, x(k + 11), S42, &HBD3AF235
II c, d, a, b, x(k + 2), S43, &H2AD7D2BB
II b, c, d, a, x(k + 9), S44, &HEB86D391
a = AddUnsigned(a, AA)
b = AddUnsigned(b, BB)
c = AddUnsigned(c, CC)
d = AddUnsigned(d, DD)
Next
MD5 = LCase(WordToHex(a) & WordToHex(b) & WordToHex(c) & WordToHex(d))
End Function
One additional thing that has not been covered in previous answers and that often cause issues on Windows and stopped me from installing some package despite running as admin is that you get the same permission denied error if there is another program that use some of the files you (or pip install
) try to access. This is a really stupid "feature" of Windows that pops up many times, e.g. when trying to move some files.
In addition I have no clue how to figure out which program locks a particular file, so the easiest ting to do is to reboot and do the installation before starting anything, in particular before running e.g. Spyder or any other Python-based software. You can also try to close all programs, but it can be tricky to know which one actually holds a file. For a directory for example, it is enough that you have an Explorer window open at that directory.
Normally, it is included. However, as @ngn999 said, if your python has been built from source manually, you'll have to add it.
Here is an example of a script that will setup an encapsulated version (virtual environment) of Python3 in your user directory with an encapsulated version of sqlite3.
INSTALL_BASE_PATH="$HOME/local"
cd ~
mkdir build
cd build
[ -f Python-3.6.2.tgz ] || wget https://www.python.org/ftp/python/3.6.2/Python-3.6.2.tgz
tar -zxvf Python-3.6.2.tgz
[ -f sqlite-autoconf-3240000.tar.gz ] || wget https://www.sqlite.org/2018/sqlite-autoconf-3240000.tar.gz
tar -zxvf sqlite-autoconf-3240000.tar.gz
cd sqlite-autoconf-3240000
./configure --prefix=${INSTALL_BASE_PATH}
make
make install
cd ../Python-3.6.2
LD_RUN_PATH=${INSTALL_BASE_PATH}/lib configure
LDFLAGS="-L ${INSTALL_BASE_PATH}/lib"
CPPFLAGS="-I ${INSTALL_BASE_PATH}/include"
LD_RUN_PATH=${INSTALL_BASE_PATH}/lib make
./configure --prefix=${INSTALL_BASE_PATH}
make
make install
cd ~
LINE_TO_ADD="export PATH=${INSTALL_BASE_PATH}/bin:\$PATH"
if grep -q -v "${LINE_TO_ADD}" $HOME/.bash_profile; then echo "${LINE_TO_ADD}" >> $HOME/.bash_profile; fi
source $HOME/.bash_profile
Why do this? You might want a modular python environment that you can completely destroy and rebuild without affecting your managed package installation. This would give you an independent development environment. In this case, the solution is to install sqlite3 modularly too.
Best aproach for me was:
private void grid_receptie_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
int X = 1;
foreach(DataGridViewRow row in grid_receptie.Rows)
{
row.Cells["NR_CRT"].Value = X;
X++;
}
}
.container
s.container
s you want to have a full-width background in a div
Fiddles: Simple: https://jsfiddle.net/vLhc35k4/ , Container borders: https://jsfiddle.net/vLhc35k4/1/
HTML:
<div class="container">
<h2>Section 1</h2>
</div>
<div class="specialBackground">
<div class="container">
<h2>Section 2</h2>
</div>
</div>
CSS: .specialBackground{ background-color: gold; /*replace with own background settings*/ }
Many people will (wrongly) suggest, that you should use nested containers.
Well, you should NOT.
They are not ment to be nested. (See to "Containers" section in the docs)
div
is a block element, which by default spans to the full width of a document body - there is the full-width feature. It also has a height of it's content (if you don't specify otherwise).
The bootstrap containers are not required to be direct children of a body, they are just containers with some padding and possibly some screen-width-variable fixed widths.
If a basic grid .container
has some fixed width it is also auto-centered horizontally.
So there is no difference whether you put it as a:
div
that is a direct child of a body.By "basic" div
I mean div
that does not have a CSS altering his border, padding, dimensions, position or content size. Really just a HTML element with display: block;
CSS and possibly background.
But of course setting vertical-like CSS (height, padding-top, ...) should not break the bootstrap grid :-)
...All over it's own website and in it's "JUMBOTRON" example:
http://getbootstrap.com/examples/jumbotron/
While I think this compiler error is a good thing, there is a way you can work around it. Use a condition you know will be true:
public void myMethod(){
someCodeHere();
if(1 < 2) return; // compiler isn't smart enough to complain about this
moreCodeHere();
}
The compiler is not smart enough to complain about that.
position: absolute
will position the element by coordinates, relative to the closest positioned ancestor, i.e. the closest parent which isn't position: static
.
Have your four divs nested inside the target div, give the target div position: relative
, and use position: absolute
on the others.
Structure your HTML similar to this:
<div id="container">
<div class="top left"></div>
<div class="top right"></div>
<div class="bottom left"></div>
<div class="bottom right"></div>
</div>
And this CSS should work:
#container {
position: relative;
}
#container > * {
position: absolute;
}
.left {
left: 0;
}
.right {
right: 0;
}
.top {
top: 0;
}
.bottom {
bottom: 0;
}
...
I think it is platform dependent. When developing in .Net MVC, I use bootstrap style lower case and hyphens for class names, but for ids I use PascalCase.
The reasoning for this is that my views are backed by strongly typed view models. Properties of C# models are pascal case. For the sake of model binding with MVC it makes sense that the names of HTML elements that bind to the model are consistent with the view model properties which are pascal case. For simplicity my ids are use the same naming convention as element names except for radio buttons and check boxes which require unique ids for each element in the named input group.
<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>
Easy as that.
Or without JS
<a href="http://yahoo.com" target="_blank">test</a>
My favorite way to handle a thread is to encapsulate it inside a C++ object. Here's an example:
class MyThreadClass
{
public:
MyThreadClass() {/* empty */}
virtual ~MyThreadClass() {/* empty */}
/** Returns true if the thread was successfully started, false if there was an error starting the thread */
bool StartInternalThread()
{
return (pthread_create(&_thread, NULL, InternalThreadEntryFunc, this) == 0);
}
/** Will not return until the internal thread has exited. */
void WaitForInternalThreadToExit()
{
(void) pthread_join(_thread, NULL);
}
protected:
/** Implement this method in your subclass with the code you want your thread to run. */
virtual void InternalThreadEntry() = 0;
private:
static void * InternalThreadEntryFunc(void * This) {((MyThreadClass *)This)->InternalThreadEntry(); return NULL;}
pthread_t _thread;
};
To use it, you would just create a subclass of MyThreadClass with the InternalThreadEntry() method implemented to contain your thread's event loop. You'd need to call WaitForInternalThreadToExit() on the thread object before deleting the thread object, of course (and have some mechanism to make sure the thread actually exits, otherwise WaitForInternalThreadToExit() would never return)
How about something like:
var myCss = $(element).attr('css');
myCss = myCss.replace('background-color: '+$(element).css('background-color')+';', '');
if(myCss == '') {
$(element).removeAttr('css');
} else {
$(element).attr('css', myCss);
}
I think you are using 'global' incorrectly. See Python reference. You should declare variable without global and then inside the function when you want to access global variable you declare it global yourvar
.
#!/usr/bin/python
total
def checkTotal():
global total
total = 0
See this example:
#!/usr/bin/env python
total = 0
def doA():
# not accessing global total
total = 10
def doB():
global total
total = total + 1
def checkTotal():
# global total - not required as global is required
# only for assignment - thanks for comment Greg
print total
def main():
doA()
doB()
checkTotal()
if __name__ == '__main__':
main()
Because doA()
does not modify the global total the output is 1 not 11.
Apologies for my previously mixed up answer.
Here is how to do:
myTreeView.SelectedNode = myTreeNode;
I have tested the code below and it works:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
treeView1.Nodes.Add("1", "1");
treeView1.Nodes.Add("2", "2");
treeView1.Nodes[0].Nodes.Add("1-1", "1-1");
TreeNode treeNode = treeView1.Nodes[0].Nodes.Add("1-2", "1-3");
treeView1.SelectedNode = treeNode;
MessageBox.Show(treeNode.IsSelected.ToString());
}
}
This related question's answer provided the solution for me... it was just a dumb mistake:
Remember to commit first!
https://stackoverflow.com/a/7572252
If you have not yet committed to your local repo, there is nothing to push, but the Git error message you get back doesn't help you too much.
the file is a native DLL which means you can't add it to a .NET project via Add Reference... you can use it via DllImport (see http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute.aspx)
I noticed this issue recently and it is frustrating that excel changes a blank string into a 0. I do not think that a formula should solve this issue because adding more logic to a complex formula may be cumbersome and might even end up breaking the original formula. I have two non formula options below.
If you want to keep the formulas in the cells and have them return 0 instead of "" use the following Click Path:
Scroll to "Display options for this worksheet:"
I also want to give a simple manual solution if you want to change a value (as opposed to a formula) from 0 to a blank string. This solution is better than Find and Replace because it will not replace a number like 101 with 11.
The other data will remain if you used the filter properly and the back button is always there if something goes wrong. I understand option 2 is very manual and "unelegant" but it does successfully convert a 0 into a blank string and it may relieve a frustrated individual who does not want to use an if statement.
I personally learned something exploring this (very dry) excel issue today and I am personally using these methods moving forward. A quick macro of option 2 could be a good option if this is a frequent task for an intermediate excel user.
as a complementary answer to @Navid_pdp11, which will enable to select the first visible item and work on document load as well. put the following below your body tag
<script>
$('#mainCat').on('change', function() {
let selected = $(this).val();
$("#expertCat option").each(function(){
let element = $(this) ;
if (element.data("tag") != selected){
element.removeClass('visible');
element.addClass('hidden');
element.hide() ;
}else{
element.removeClass('hidden');
element.addClass('visible');
element.show();
}
});
let expertCat = $('#expertCat');
expertCat.prop('selectedIndex',expertCat.find("option.visible:eq(0)").index());
}).triggerHandler('change');
</script>
You can use this, just think Job is the name of the model to which you are adding index cader_id:
class AddCaderIdToJob < ActiveRecord::Migration[5.2]
def change
change_table :jobs do |t|
t.integer :cader_id
t.index :cader_id
end
end
end
In my case this format worked on latest version of jQuery:
$('img#post_image_preview').src;
Below regexs can be used to check if a string has only number or not:
if (str.matches(".*[^0-9].*")) or if (str.matches(".*\\D.*"))
Both conditions above will return true
if String containts non-numbers. On false
, string has only numbers.
Step 1:Execute the query
column username format 'a10'
column osuser format 'a10'
column module format 'a16'
column program_name format 'a20'
column program format 'a20'
column machine format 'a20'
column action format 'a20'
column sid format '9999'
column serial# format '99999'
column spid format '99999'
set linesize 200
set pagesize 30
select
a.sid,a.serial#,a.username,a.osuser,c.start_time,
b.spid,a.status,a.machine,
a.action,a.module,a.program
from
v$session a, v$process b, v$transaction c,
v$sqlarea s
Where
a.paddr = b.addr
and a.saddr = c.ses_addr
and a.sql_address = s.address (+)
and to_date(c.start_time,'mm/dd/yy hh24:mi:ss') <= sysdate - (15/1440) -- running for 15 minutes
order by c.start_time
/
Step 2: desc v$session
Step 3:select sid, serial#,SQL_ADDRESS, status,PREV_SQL_ADDR from v$session where sid='xxxx' //(enter the sid value)
Step 4: select sql_text from v$sqltext where address='XXXXXXXX';
Step 5: select piece, sql_text from v$sqltext where address='XXXXXX' order by piece;
in normal time, checkboxes return an on/off value.
you can verify it with this code:
<form action method="POST">
<input type="checkbox" name="hello"/>
</form>
<?php
if(isset($_POST['hello'])) echo('<p>'.$_POST['hello'].'</p>');
?>
this will return
<p>off</p>
or
<p>on</p>
Just to add to the conversation, I have found a more elegant way to change the color of the box plot by iterating over the dictionary of the object itself
import numpy as np
import matplotlib.pyplot as plt
def color_box(bp, color):
# Define the elements to color. You can also add medians, fliers and means
elements = ['boxes','caps','whiskers']
# Iterate over each of the elements changing the color
for elem in elements:
[plt.setp(bp[elem][idx], color=color) for idx in xrange(len(bp[elem]))]
return
a = np.random.uniform(0,10,[100,5])
bp = plt.boxplot(a)
color_box(bp, 'red')
Cheers!
<input type="number" step="1" ...
By adding the step
attribute, you restrict input to integers.
Of course you should always validate on the server as well. Except under carefully controlled conditions, everything received from a client needs to be treated as suspect.
a rapid response not tested on several brosers, works on gg chrome / win
-> On focus event -> show/hide password
<input type="password" name="password">
script jQuery
// show on focus
$('input[type="password"]').on('focusin', function(){
$(this).attr('type', 'text');
});
// hide on focus Out
$('input[type="password"]').on('focusout', function(){
$(this).attr('type', 'password');
});
You dont see alphabets magical appearance and disappearance on key down. This works on mouse paste too.
$('#txtInt').bind('input propertychange', function () {
$(this).val($(this).val().replace(/[^0-9]/g, ''));
});
The first thing to do would probably be to replace every mysql_*
function call with its equivalent mysqli_*
, at least if you are willing to use the procedural API -- which would be the easier way, considering you already have some code based on the MySQL API, which is a procedural one.
To help with that, the MySQLi Extension Function Summary is definitely something that will prove helpful.
For instance:
mysql_connect
will be replaced by mysqli_connect
mysql_error
will be replaced by mysqli_error
and/or mysqli_connect_error
, depending on the contextmysql_query
will be replaced by mysqli_query
Note: For some functions, you may need to check the parameters carefully: Maybe there are some differences here and there -- but not that many, I'd say: both mysql and mysqli are based on the same library (libmysql ; at least for PHP <= 5.2)
For instance:
mysql_select_db
once connected, to indicate on which database you want to do your queriesmysqli_connect
.mysqli_select_db
function that you can use, if you prefer.WARNING:
git clean -f
will remove untracked files, meaning they're gone for good since they aren't stored in the repository. Make sure you really want to remove all untracked files before doing this.
Try this and see git clean -f
.
git reset --hard
will not remove untracked files, where as git-clean
will remove any files from the tracked root directory that are not under Git tracking.
Alternatively, as @Paul Betts said, you can do this (beware though - that removes all ignored files too)
git clean -df
git clean -xdf
CAUTION! This will also delete ignored filesI think you just need to give it a parent container... even if that container's height is defined in percentage. This seams to work just fine: JSFiddle
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
.wrapper {
width: 100%;
height: 100%;
}
.container {
width: 100%;
height: 50%;
}
using Microsoft.Office.Interop.Excel;
string path = "C:\\Projects\\ExcelSingleValue\\Test.xlsx ";
Application excel = new Application();
Workbook wb = excel.Workbooks.Open(path);
Worksheet excelSheet = wb.ActiveSheet;
//Read the first cell
string test = excelSheet.Cells[1, 1].Value.ToString();
wb.Close();
This example used the 'Microsoft Excel 15.0 Object Library' but may be compatible with earlier versions of Interop and other libraries.
If you have homebrew you can also install via brew
$ brew install docker-compose
This is a good way to install on a Mac OS system
This error happens when the resource is busy. Check if you have any referential constraints in the query. Or even the tables that you have mentioned in the query may be busy. They might be engaged with some other job which will be definitely listed in the following query results:
SELECT * FROM V$SESSION WHERE STATUS = 'ACTIVE'
Find the SID,
SELECT * FROM V$OPEN_CURSOR WHERE SID = --the id
This is how I handle iPhone (and similar) devices [not iPad]:
In my CSS file:
@media only screen and (max-width: 480px), only screen and (max-device-width: 480px) {
/* CSS overrides for mobile here */
}
In the head of my HTML document:
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
You probably want to have LI rather than the UL have the background-color:
.selected li {
background-color: red;
}
Then you want to have a dynamic class for the UL:
<ul ng-repeat="vote in votes" ng-click="setSelected()" class="{{selected}}">
Now you need to update the $scope.selected when clicking the row:
$scope.setSelected = function() {
console.log("show", arguments, this);
this.selected = 'selected';
}
and then un-select the previously highlighted row:
$scope.setSelected = function() {
// console.log("show", arguments, this);
if ($scope.lastSelected) {
$scope.lastSelected.selected = '';
}
this.selected = 'selected';
$scope.lastSelected = this;
}
Working solution:
use this
if (userProfile.AccountType == AccountType.Retailer)
{
...
}
If you want to get int from your AccountType enum and compare it (don't know why) do this:
if((int)userProfile.AccountType == 1)
{
...
}
Objet reference not set to an instance of an object
exception is because your userProfile is null and you are getting property of null. Check in debug why it's not set.
EDIT (thanks to @Rik and @KonradMorawski) :
Maybe you can do some check before:
if(userProfile!=null)
{
}
or
if(userProfile==null)
{
throw new ArgumentNullException(nameof(userProfile)); // or any other exception
}
In one word: no. The only way to stretch an image is with the <img>
tag. You'll have to be creative.
This used to be true in 2008, when the answer was written. Today modern browsers support background-size
which solves this problem. Beware that IE8 doesn't support it.
Lets assume
private string isChecked;
private webElement e;
isChecked =e.findElement(By.tagName("input")).getAttribute("checked");
if(isChecked=="true")
{
}
else
{
}
Hope this answer will be help for you. Let me know, if have any clarification in CSharp Selenium web driver.
Honestly, I would setup replication for this, as if you don't lock tables you will get inconsistent data out of the dump.
If the dump takes longer time, tables which were already dumped might have changed along with some table which is only about to be dumped.
So either lock the tables or use replication.
System images are pre-installed Android operating systems, and are only used by emulators. If you use your real Android device for debugging, you no longer need them, so you can remove them all.
The cleanest way to remove them is using SDK Manager. Open up SDK Manager and uncheck those system images and then apply.
Also feel free to remove other components (e.g. old SDK levels) that are of no use.
const destroy = container => {
document.getElementById(container).innerHTML = '';
};
Faster previous
const destroyFast = container => {
const el = document.getElementById(container);
while (el.firstChild) el.removeChild(el.firstChild);
};
This option is fine for me :
ChromeOptions options = new ChromeOptions();
options.addArguments("start-fullscreen");
This option works on all OS.
I understand that the answer was useful however for some reason it does not work for me however I have moved the situation with the following code and it is perfect
<?php
$codigoarticulo = $_POST['codigoarticulo'];
$nombrearticulo = $_POST['nombrearticulo'];
$seccion = $_POST['seccion'];
$precio = $_POST['precio'];
$fecha = $_POST['fecha'];
$importado = $_POST['importado'];
$paisdeorigen = $_POST['paisdeorigen'];
try {
$server = 'mysql: host=localhost; dbname=usuarios';
$user = 'root';
$pass = '';
$base = new PDO($server, $user, $pass);
$base->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$base->query("SET character_set_results = 'utf8',
character_set_client = 'utf8',
character_set_connection = 'utf8',
character_set_database = 'utf8',
character_set_server = 'utf8'");
$base->exec("SET character_set_results = 'utf8',
character_set_client = 'utf8',
character_set_connection = 'utf8',
character_set_database = 'utf8',
character_set_server = 'utf8'");
$sql = "
INSERT INTO productos
(CÓDIGOARTÍCULO, NOMBREARTÍCULO, SECCIÓN, PRECIO, FECHA, IMPORTADO, PAÍSDEORIGEN)
VALUES
(:c_art, :n_art, :sec, :pre, :fecha_art, :import, :p_orig)";
// SE ejecuta la consulta ben prepare
$result = $base->prepare($sql);
// se pasan por parametros aqui
$result->bindParam(':c_art', $codigoarticulo);
$result->bindParam(':n_art', $nombrearticulo);
$result->bindParam(':sec', $seccion);
$result->bindParam(':pre', $precio);
$result->bindParam(':fecha_art', $fecha);
$result->bindParam(':import', $importado);
$result->bindParam(':p_orig', $paisdeorigen);
$result->execute();
echo 'Articulo agregado';
} catch (Exception $e) {
echo 'Error';
echo $e->getMessage();
} finally {
}
?>
If you got only one column in the range to clean, just add "(1)" to the end. It indicates in wich column of the range Excel will remove the duplicates. Something like:
Sub norepeat()
Range("C8:C16").RemoveDuplicates (1)
End Sub
Regards
I know this topic is old but I think I can contribute. You can trigger the default behavior of an event on a specific element any time in your handler function if you already know that behavior. For example, when you trigger the click event on the reset button, you actually call the reset function on the closest form as the default behavior. In your handler function, after using the preventDefault function, you can recall the default behavior by calling the reset function on the closest form anywhere in your handler code.
Another great fix here to configure NPM properly, run the following commands :
npm config set prefix '~/.npm_packages'
PATH=$PATH:$HOME/.npm_packages/bin; export PATH
Thanks to the solution provided by @yogihosting I was able to achieve similar result from schemaless columns of mysql with codes shown below:
// @params - will be bound to named query parameters
$criteria = [];
$criteria['latitude'] = '9.0285183';
$criteria['longitude'] = '7.4869546';
$criteria['distance'] = 500;
$criteria['skill'] = 'software developer';
// Get doctrine connection
$conn = $this->getEntityManager()->getConnection();
$sql = '
SELECT DISTINCT m.uuid AS phone, (((acos(sin((:latitude*pi()/180)) * sin((JSON_EXTRACT(m.location, "$.latitude")*pi()/180))+cos((:latitude*pi()/180)) *
cos((JSON_EXTRACT(m.location, "$.latitude")*pi()/180)) *
cos(((:longitude - JSON_EXTRACT(m.location, "$.longitude"))*pi()/180))))*180/pi())*60*1.1515*1.609344) AS distance FROM member_profile AS m
INNER JOIN member_card_subscription mcs ON mcs.primary_identity = m.uuid
WHERE mcs.end > now() AND JSON_SEARCH(m.skill_logic, "one", :skill) IS NOT NULL AND (((acos(sin((:latitude*pi()/180)) * sin((JSON_EXTRACT(m.location, "$.latitude")*pi()/180))+cos((:latitude*pi()/180)) *
cos((JSON_EXTRACT(m.location, "$.latitude")*pi()/180)) *
cos(((:longitude - JSON_EXTRACT(m.location, "$.longitude"))*pi()/180))))*180/pi())*60*1.1515*1.609344) <= :distance ORDER BY distance
';
$stmt = $conn->prepare($sql);
$stmt->execute(['latitude'=>$criteria['latitude'], 'longitude'=>$criteria['longitude'], 'skill'=>$criteria['skill'], 'distance'=>$criteria['distance']]);
var_dump($stmt->fetchAll());
Please note the above code snippet is using doctrine DB connection and PHP
long
type in Python 2.x uses arbitrary precision arithmetic and has no such thing as maximum possible value. It is limited by the available memory. Python 3.x has no special type for values that cannot be represented by the native machine integer — everything is int
and conversion is handled behind the scenes.
dynamic dynJson = JsonConvert.DeserializeObject(json);
foreach (var item in dynJson)
{
Console.WriteLine("{0} {1} {2} {3}\n", item.id, item.displayName,
item.slug, item.imageUrl);
}
or
var list = JsonConvert.DeserializeObject<List<MyItem>>(json);
public class MyItem
{
public string id;
public string displayName;
public string name;
public string slug;
public string imageUrl;
}
This may help:
This creates a node that takes a 2D List (list of list items) and pushes them into the excel spreadsheet. make sure the IN[]s are present or will throw and exception.
this is a re-write of the Revit excel dynamo node for excel 2013 as the default prepackaged node kept breaking. I also have a similar read node. The excel syntax in Python is touchy.
thnx @CodingNinja - updated : )
###Export Excel - intended to replace malfunctioning excel node
import clr
clr.AddReferenceByName('Microsoft.Office.Interop.Excel, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c')
##AddReferenceGUID("{00020813-0000-0000-C000-000000000046}") ''Excel C:\Program Files\Microsoft Office\Office15\EXCEL.EXE
##Need to Verify interop for version 2015 is 15 and node attachemnt for it.
from Microsoft.Office.Interop import * ##Excel
################################Initialize FP and Sheet ID
##Same functionality as the excel node
strFileName = IN[0] ##Filename
sheetName = IN[1] ##Sheet
RowOffset= IN[2] ##RowOffset
ColOffset= IN[3] ##COL OFfset
Data=IN[4] ##Data
Overwrite=IN[5] ##Check for auto-overwtite
XLVisible = False #IN[6] ##XL Visible for operation or not?
RowOffset=0
if IN[2]>0:
RowOffset=IN[2] ##RowOffset
ColOffset=0
if IN[3]>0:
ColOffset=IN[3] ##COL OFfset
if IN[6]<>False:
XLVisible = True #IN[6] ##XL Visible for operation or not?
################################Initialize FP and Sheet ID
xlCellTypeLastCell = 11 #####define special sells value constant
################################
xls = Excel.ApplicationClass() ####Connect with application
xls.Visible = XLVisible ##VISIBLE YES/NO
xls.DisplayAlerts = False ### ALerts
import os.path
if os.path.isfile(strFileName):
wb = xls.Workbooks.Open(strFileName, False) ####Open the file
else:
wb = xls.Workbooks.add# ####Open the file
wb.SaveAs(strFileName)
wb.application.visible = XLVisible ####Show Excel
try:
ws = wb.Worksheets(sheetName) ####Get the sheet in the WB base
except:
ws = wb.sheets.add() ####If it doesn't exist- add it. use () for object method
ws.Name = sheetName
#################################
#lastRow for iterating rows
lastRow=ws.UsedRange.SpecialCells(xlCellTypeLastCell).Row
#lastCol for iterating columns
lastCol=ws.UsedRange.SpecialCells(xlCellTypeLastCell).Column
#######################################################################
out=[] ###MESSAGE GATHERING
c=0
r=0
val=""
if Overwrite == False : ####Look ahead for non-empty cells to throw error
for r, row in enumerate(Data): ####BASE 0## EACH ROW OF DATA ENUMERATED in the 2D array #range( RowOffset, lastRow + RowOffset):
for c, col in enumerate (row): ####BASE 0## Each colmn in each row is a cell with data ### in range(ColOffset, lastCol + ColOffset):
if col.Value2 >"" :
OUT= "ERROR- Cannot overwrite"
raise ValueError("ERROR- Cannot overwrite")
##out.append(Data[0]) ##append mesage for error
############################################################################
for r, row in enumerate(Data): ####BASE 0## EACH ROW OF DATA ENUMERATED in the 2D array #range( RowOffset, lastRow + RowOffset):
for c, col in enumerate (row): ####BASE 0## Each colmn in each row is a cell with data ### in range(ColOffset, lastCol + ColOffset):
ws.Cells[r+1+RowOffset,c+1+ColOffset].Value2 = col.__str__()
##run macro disbled for debugging excel macro
##xls.Application.Run("Align_data_and_Highlight_Issues")
Perhaps a combination of these plugins may come in handy:
You can use iteritems()
:
for name, values in df.iteritems():
print('{name}: {value}'.format(name=name, value=values[0]))
You can try something like this
var access_token = driver.findElement(webdriver.By.name("AccToken"))
var access_token_getTextFunction = function() {
access_token.getText().then(function(value) {
console.log(value);
return value;
});
}
Than you can call this function where you want to get the value..
This regex can help you to check your email-address according to all the criteria which gmail.com used.
var re = /^\w+([-+.'][^\s]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
var emailFormat = re.test($("#email").val()); // This return result in Boolean type
if (emailFormat) {}
The value you have passed as the file descriptor is not valid. It is either negative or does not represent a currently open file or socket.
So you have either closed the socket before calling write()
or you have corrupted the value of 'sockfd' somewhere in your code.
It would be useful to trace all calls to close()
, and the value of 'sockfd' prior to the write()
calls.
Your technique of only printing error messages in debug mode seems to me complete madness, and in any case calling another function between a system call and perror()
is invalid, as it may disturb the value of errno
. Indeed it may have done so in this case, and the real underlying error may be different.
PUT
$data = array('username'=>'dog','password'=>'tall');
$data_json = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
POST
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
GET See @Dan H answer
DELETE
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
I did downgrade the node version from 12 to 10
EDIT
This error occurred with me because I was using node version 12. When I downgrade to version 10.16.5 this error stops. This error happened in my local env, but in prod and staging, it not happens. In prod and staging node version is 10.x so I just do this and I didn't need to update any package in my package.json
Well, you pretty much gave yourself the answer. In your CSS give the containing element a min-width. If you have to support IE6 you can use the min-width-trick:
#container {
min-width:800px;
width: auto !important;
width:800px;
}
That will effectively give you 800px min-width in IE6 and any up-to-date browsers.
As of react-native 0.57, none of the previously provided answers will work anymore, as the directories in which gradle expects to find the bundle and the assets have changed.
The simplest way to build a debug build is without using the react-native bundle
command at all, but by simply modifying your app/build.gradle
file.
Inside the project.ext.react
map in the app/build.gradle
file, add the bundleInDebug: true
entry.
If you want it to not be a --dev
build (no warnings and minified bundle) then you should also add the devDisabledInDebug: true
entry to the same map.
If for some reason you need to or want to use the react-native bundle
command to create the bundle and then the ./gradlew assembleDebug
to create the APK with the bundle and the assets you have to make sure to put the bundle and the assets in the correct paths, where gradle can find them.
As of react-native 0.57 those paths are
android/app/build/generated/assets/react/debug/index.android.js
for the bundle
and android/app/build/generated/res/react/debug
for the assets. So the full commands for manually bundling and building the APK with the bundle and assets are:
react-native bundle --dev false --platform android --entry-file index.js --bundle-output ./android/app/build/generated/assets/react/debug/index.android.bundle --assets-dest ./android/app/build/res/react/debug
and then
./gradlew assembleDebug
Note that that paths where gradle looks for the bundle and the assets might be subject to change. To find out where those paths are, look at the react.gradle
file in your node_modules/react-native
directory. The lines starting with def jsBundleDir =
and def resourcesDir =
specify the directories where gradle looks for the bundle and the assets respectively.
I think the differences are:
Code first
Database first
Model first
I expect that in case of EF 4.1 there are several other features related to Code First vs. Model/Database first. Fluent API used in Code first doesn't offer all features of EDMX. I expect that features like stored procedures mapping, query views, defining views etc. works when using Model/Database first and DbContext
(I haven't tried it yet) but they don't in Code first.
for element in somelist:
do_action(element)
somelist[:] = (x for x in somelist if not check(x))
If you really need to do it in one pass without copying the list
i=0
while i < len(somelist):
element = somelist[i]
do_action(element)
if check(element):
del somelist[i]
else:
i+=1
You can't call free
on the pointers returned from strsep
. Those are not individually allocated strings, but just pointers into the string s
that you've already allocated. When you're done with s
altogether, you should free it, but you do not have to do that with the return values of strsep
.
To see which ports are available on your machine run:
C:> netstat -an |find /i "listening"
At the command prompt try:
mysql -u root -p
give the password when prompted.
I am adding this A because I got caught with a bizarre version of this which really had me scratching my head for about a hour until I spotted the root cause. My load was failing because of multiple repeats of this format
<path>/linit.o:(.rodata1.libs+0x50): multiple definition of `lua_lib_BASE'
<path>/linit.o:(.rodata1.libs+0x50): first defined here
I turned out to be a bug in my Makefile magic where I had a list of C files and using vpath etc., so the compiles would pick them up from the correct directory in hierarchy. However one C file was repeated in the list, at the end of one line and the start of the next so the gcc load generated by the make had the .o
file twice on the command line. Durrrrh. The multiple definitions were from multiple occurances of the same file. The linker ignored duplicates apart from static initialisers!
Well, from sourceTree I couldn't resolve this issue but I created sshkey from bash and at least it works from git-bash.
https://confluence.atlassian.com/bitbucket/set-up-an-ssh-key-728138079.html
A lot of the solutions offered here do not seem to work anymore. I'm currently on a chromebook and wanted to view an HTML5 banner. This seems impossible now through Google Drive or other apps (as mentioned in previous comments).
The method I ended up using to view the HTML5 was the following:
There may well an easier way, but this way is pretty good too. Hope it helps and worked well for me.
A Kotlin extension + some padding around the drawable
fun TextView.addDrawable(drawable: Int) {
val imgDrawable = ContextCompat.getDrawable(context, drawable)
compoundDrawablePadding = 32
setCompoundDrawablesWithIntrinsicBounds(imgDrawable, null, null, null)
}
Sounds like mssql jdbc is buffering the entire resultset for you. You can add a connect string parameter saying selectMode=cursor or responseBuffering=adaptive. If you are on version 2.0+ of the 2005 mssql jdbc driver then response buffering should default to adaptive.
I had the same problem in Eclipse, so maybe what I did to resolve it can help you. In the project properties I had to set the launch configurations to the file that contains the main-method (I don't know why it wasn't set to the right file automatically).
True, but after turning json to xml with xmlspy, you can use trang application (http://www.thaiopensource.com/relaxng/trang.html) to create an xsd from xml file(s).
You can use sort() function. sort() exists in algorithm header file
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
string str = "sharlock";
sort(str.begin(), str.end());
cout<<str<<endl;
return 0;
}
Output:
achklors
char check1[10], check2[10];
int foo;
do{
printf(">> ");
scanf(" %s", check1);
foo = strtol(check1, NULL, 10); // convert the string to decimal number
sprintf(check2, "%d", foo); // re-convert "foo" to string for comparison
} while (!(strcmp(check1, check2) == 0 && 0 < foo && foo < 24)); // repeat if the input is not number
If the input is number, you can use foo
as your input.
Following worked on M1
ProductName: macOS
ProductVersion: 11.1
BuildVersion: 20C69
% compaudit
/opt/homebrew/share
Changed group permission from 775 to 755
% sudo chmod 755 /opt/homebrew/share
drwxr-xr-x 33 xenea admin 1056 Feb 2 01:28 share
OpenSSL provides a passwd command that can encrypt but doesn't decrypt as it only does hashes. You could also download something like aesutil so you can use a capable and well-known symmetric encryption routine.
For example:
#!/bin/sh
# using aesutil
SALT=$(mkrand 15) # mkrand generates a 15-character random passwd
MYENCPASS="i/b9pkcpQAPy7BzH2JlqHVoJc2mNTBM=" # echo "passwd" | aes -e -b -B -p $SALT
MYPASS=$(echo "$MYENCPASS" | aes -d -b -p $SALT)
# and usage
serverControl.sh -u admin -p $MYPASS -c shutdown
Assuming that files with those names exist in multiple places in the directory tree and you want to preserve all of them:
find . -type f ! -regex ".*/\(textfile.txt\|backup.tar.gz\|script.php\|database.sql\|info.txt\)" -delete
This date function below achieves the desired effect without an additional script library. Basically it's just a simple date component concatenation in the right format, and augmenting of the Date object's prototype.
Date.prototype.dateToISO8601String = function() {
var padDigits = function padDigits(number, digits) {
return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
}
var offsetMinutes = this.getTimezoneOffset();
var offsetHours = offsetMinutes / 60;
var offset= "Z";
if (offsetHours < 0)
offset = "-" + padDigits(offsetHours.replace("-","") + "00",4);
else if (offsetHours > 0)
offset = "+" + padDigits(offsetHours + "00", 4);
return this.getFullYear()
+ "-" + padDigits((this.getUTCMonth()+1),2)
+ "-" + padDigits(this.getUTCDate(),2)
+ "T"
+ padDigits(this.getUTCHours(),2)
+ ":" + padDigits(this.getUTCMinutes(),2)
+ ":" + padDigits(this.getUTCSeconds(),2)
+ "." + padDigits(this.getUTCMilliseconds(),2)
+ offset;
}
Date.dateFromISO8601 = function(isoDateString) {
var parts = isoDateString.match(/\d+/g);
var isoTime = Date.UTC(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]);
var isoDate = new Date(isoTime);
return isoDate;
}
function test() {
var dIn = new Date();
var isoDateString = dIn.dateToISO8601String();
var dOut = Date.dateFromISO8601(isoDateString);
var dInStr = dIn.toUTCString();
var dOutStr = dOut.toUTCString();
console.log("Dates are equal: " + (dInStr == dOutStr));
}
Usage:
var d = new Date();
console.log(d.dateToISO8601String());
Hopefully this helps someone else.
EDIT
Corrected UTC issue mentioned in comments, and credit to Alex for the dateFromISO8601
function.
Reading the section 3.7 of JLS well explain all you need to know about comments in Java.
There are two kinds of comments:
- /* text */
A traditional comment: all the text from the ASCII characters /* to the ASCII characters */ is ignored (as in C and C++).
- //text
An end-of-line comment: all the text from the ASCII characters // to the end of the line is ignored (as in C++).
About your question,
The first one
/**
*
*/
is used to declare Javadoc Technology.
Javadoc is a tool that parses the declarations and documentation comments in a set of source files and produces a set of HTML pages describing the classes, interfaces, constructors, methods, and fields. You can use a Javadoc doclet to customize Javadoc output. A doclet is a program written with the Doclet API that specifies the content and format of the output to be generated by the tool. You can write a doclet to generate any kind of text file output, such as HTML, SGML, XML, RTF, and MIF. Oracle provides a standard doclet for generating HTML-format API documentation. Doclets can also be used to perform special tasks not related to producing API documentation.
For more information on Doclet
refer to the API.
The second one, as explained clearly in JLS, will ignore all the text between /*
and */
thus is used to create multiline comments.
Some other things you might want to know about comments in Java
/* and */
have no special meaning in comments that begin with //
.//
has no special meaning in comments that begin with /* or /**
.Thus, the following text is a single complete comment:
/* this comment /* // /** ends here: */
This problem happened with me and sovled by just add
respond_to :html, :json
to ApplicationController file
You can Check Devise issues on Github: https://github.com/plataformatec/devise/issues/2667
On the server, try:
netstat -an
and look to see if tcp port 22
is opened (use findstr
in Windows or grep
in Unix).
The other excellent answers already answered that:
EF BB BF
But, as additional information to this, the BOM for UTF-8 could be a good way to "smell" if a string was encoded in UTF-8... Or it could be a legitimate string in any other encoding...
For example, the data [EF BB BF 41 42 43] could either be:
So while it can be cool to recognize the encoding of a file content by looking at the first bytes, you should not rely on this, as show by the example above
Encodings should be known, not divined.
The term data type is as the type of data which a particular variable can hold - it may be an integer, a character, a float, or any range of simple data storage representation. However, when we build an object oriented system, we use other data types, known as abstract data type, which represents more realistic entities.
E.g.: We might be interested in representing a 'bank account' data type, which describe how all bank account are handled in a program. Abstraction is about reducing complexity, ignoring unnecessary details.
If you set numberOfLines
to 0 (and the label to word wrap), the label will automatically wrap and use as many of lines as needed.
If you're editing a UILabel
in IB, you can enter multiple lines of text by pressing option+return to get a line break - return alone will finish editing.
The following also works:
select dump(a,1016), a from (
SELECT REGEXP_REPLACE (
CONVERT (
'3735844533120%$03 ',
'US7ASCII',
'WE8ISO8859P1'),
'[^!@/\.,;:<>#$%&()_=[:alnum:][:blank:]]') a
FROM DUAL);
Warning: this is a dangerous method! It abuses the i/o buffers in linux and with specific options of buffering it manages to work on small files. It is an interesting curiosity. But don't use it for a real situation!
Besides the -i
option of sed
you can use the tee
utility.
From man
:
tee - read from standard input and write to standard output and files
So, the solution would be:
sed s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html | tee | tee index.html
-- here the tee
is repeated to make sure that the pipeline is buffered. Then all commands in the pipeline are blocked until they get some input to work on. Each command in the pipeline starts when the upstream commands have written 1 buffer of bytes (the size is defined somewhere) to the input of the command. So the last command tee index.html
, which opens the file for writing and therefore empties it, runs after the upstream pipeline has finished and the output is in the buffer within the pipeline.
Most likely the following won't work:
sed s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html | tee index.html
-- it will run both commands of the pipeline at the same time without any blocking. (Without blocking the pipeline should pass the bytes line by line instead of buffer by buffer. Same as when you run cat | sed s/bar/GGG/
. Without blocking it's more interactive and usually pipelines of just 2 commands run without buffering and blocking. Longer pipelines are buffered.) The tee index.html
will open the file for writing and it will be emptied. However, if you turn the buffering always on, the second version will work too.
From the line
'key' => env('APP_KEY', 'SomeRandomString'),
APP_KEY
is a global environment variable that is present inside the .env
file.
You can replace the application key if you trigger
php artisan key:generate
command. This will always generate the new key.
The output may be like this:
Application key [Idgz1PE3zO9iNc0E3oeH3CHDPX9MzZe3] set successfully.
Application key [base64:uynE8re8ybt2wabaBjqMwQvLczKlDSQJHCepqxmGffE=] set successfully.
Base64 encoding should be the default in Laravel 5.4
Note that when you first create your Laravel application, key:generate is automatically called.
Hash::make()
will no longer be valid.Just use the modulus
loop through the list and run the following on each item
if(num % 2 == 0)
{
//is even
}
else
{
//is odd
}
Alternatively if you want to know if all are even you can do something like this:
bool allAreEven = lst.All(x => x % 2 == 0);
This is 2 years old, but none of them helped me.
I uninstalled my NodeJS v12.8.1 (Current) and installed a brand new v10.16.3 (LTS) and my ng build --prod
worked.
My EditText was nested several layers inside my ScrollView, which itself isn't the layout's root view. Because getTop() and getBottom() were seeming to report the coordinates within it's containing view, I had it compute the distance from the top of the ScrollView to the top of the EditText by iterating through the parents of the EditText.
// Scroll the view so that the touched editText is near the top of the scroll view
new Thread(new Runnable()
{
@Override
public
void run ()
{
// Make it feel like a two step process
Utils.sleep(333);
// Determine where to set the scroll-to to by measuring the distance from the top of the scroll view
// to the control to focus on by summing the "top" position of each view in the hierarchy.
int yDistanceToControlsView = 0;
View parentView = (View) m_editTextControl.getParent();
while (true)
{
if (parentView.equals(scrollView))
{
break;
}
yDistanceToControlsView += parentView.getTop();
parentView = (View) parentView.getParent();
}
// Compute the final position value for the top and bottom of the control in the scroll view.
final int topInScrollView = yDistanceToControlsView + m_editTextControl.getTop();
final int bottomInScrollView = yDistanceToControlsView + m_editTextControl.getBottom();
// Post the scroll action to happen on the scrollView with the UI thread.
scrollView.post(new Runnable()
{
@Override
public void run()
{
int height =m_editTextControl.getHeight();
scrollView.smoothScrollTo(0, ((topInScrollView + bottomInScrollView) / 2) - height);
m_editTextControl.requestFocus();
}
});
}
}).start();
SELECT
hat,
shoe,
boat,
0 as placeholder -- for column having 0 value
FROM
objects
--OR '' as Placeholder -- for blank column
--OR NULL as Placeholder -- for column having null value
Another thing that people may find useful...make sure to leave off ".py" from your module name. For example, if you are trying to generate documentation for 'original' in 'original.py':
yourcode_dir$ pydoc -w original.py no Python documentation found for 'original.py' yourcode_dir$ pydoc -w original wrote original.html
The HttpParams
interface isn't there for specifying query string parameters, it's for specifying runtime behaviour of the HttpClient
object.
If you want to pass query string parameters, you need to assemble them on the URL yourself, e.g.
new HttpGet(url + "key1=" + value1 + ...);
Remember to encode the values first (using URLEncoder
).
In order to avoid such error you could use CASE
+ ISNUMERIC
to handle scenarios when you cannot convert to int.
Change
CONVERT(INT, CONVERT(VARCHAR(12), a.value))
To
CONVERT(INT,
CASE
WHEN IsNumeric(CONVERT(VARCHAR(12), a.value)) = 1 THEN CONVERT(VARCHAR(12),a.value)
ELSE 0 END)
Basically this is saying if you cannot convert me to int assign value of 0 (in my example)
Alternatively you can look at this article about creating a custom function that will check if a.value
is number: http://www.tek-tips.com/faqs.cfm?fid=6423
"By default, when an application calls DriverManager.getConnection(url, ...)
and the database specified in the URL does not yet exist, a new (empty) database is created."—H2 Database.
Addendum: @Thomas Mueller shows how to Execute SQL on Connection, but I sometimes just create and populate in the code, as suggested below.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/** @see http://stackoverflow.com/questions/5225700 */
public class H2MemTest {
public static void main(String[] args) throws Exception {
Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
Statement st = conn.createStatement();
st.execute("create table customer(id integer, name varchar(10))");
st.execute("insert into customer values (1, 'Thomas')");
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery("select name from customer");
while (rset.next()) {
String name = rset.getString(1);
System.out.println(name);
}
}
}
It's recommended not to use the <Button>
tag. Use the <Input type='Button' onclick='return false;'>
tag instead. (Using the "return false" should indeed not send the form.)
Some reference material
Update for Swift 3.0 and higher
//
// Step 1:- Create a method in AppDelegate.swift
//
func someMethodInAppDelegate() {
print("someMethodInAppDelegate called")
}
calling above method from your controller by followings
//
// Step 2:- Getting a reference to the AppDelegate & calling the require method...
//
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
appDelegate.someMethodInAppDelegate()
}
Output:
mysqli_select_db()
should have 2 parameters, the connection link and the database name -
mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));
Using mysqli_error
in the die statement will tell you exactly what is wrong as opposed to a generic error message.
This option comes in curl 7.73.0:
curl --create-dirs -O --output-dir /tmp/receipes https://example.com/pancakes.jpg
See the docs about querying.
It would be:
$or: [{a: 5}, {a: 6}] // (a = 5 OR a = 6)
I was intrigued by the answer from @Jerry Coffin, which suggested that the ordered map would exhibit performance increases on long strings, after some experimentation (which can be downloaded from pastebin), I've found that this seems to hold true only for collections of random strings, when the map is initialised with a sorted dictionary (which contain words with considerable amounts of prefix-overlap), this rule breaks down, presumably because of the increased tree depth necessary to retrieve value. The results are shown below, the 1st number column is insert time, 2nd is fetch time.
g++ -g -O3 --std=c++0x -c -o stdtests.o stdtests.cpp
g++ -o stdtests stdtests.o
gmurphy@interloper:HashTests$ ./stdtests
# 1st number column is insert time, 2nd is fetch time
** Integer Keys **
unordered: 137 15
ordered: 168 81
** Random String Keys **
unordered: 55 50
ordered: 33 31
** Real Words Keys **
unordered: 278 76
ordered: 516 298
SEND Button logic:
string fromaddr = "[email protected]";
string toaddr = TextBox1.Text;//TO ADDRESS HERE
string password = "YOUR PASSWROD";
MailMessage msg = new MailMessage();
msg.Subject = "Username &password";
msg.From = new MailAddress(fromaddr);
msg.Body = "Message BODY";
msg.To.Add(new MailAddress(TextBox1.Text));
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
NetworkCredential nc = new NetworkCredential(fromaddr,password);
smtp.Credentials = nc;
smtp.Send(msg);
This code work 100%. If you have antivirus in your system or firewall that restrict sending mails from your system so disable your antivirus and firewall. After this run this code... In this above code TextBox1.Text
control is used for TOaddress
.
Use the below code to convert a php array to CSV
<?php
$ROW=db_export_data();//Will return a php array
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=test.csv");
$fp = fopen('php://output', 'w');
foreach ($ROW as $row) {
fputcsv($fp, $row);
}
fclose($fp);
I made a small investigation because I am also interested in the solution.
According to http://books.sonatype.com/mvnref-book/reference/running-sect-options.html#running-sect-verbose-option
Currently maven 3.1.x uses SLF4J to log to the System.out . You can modify the logging settings at the file:
${MAVEN_HOME}/conf/logging/simplelogger.properties
According to the page : http://maven.apache.org/maven-logging.html
I think you should be able to setup the default Log level of the simple logger via a command line parameter, like this:
$ mvn clean package -Dorg.slf4j.simpleLogger.defaultLogLevel=debug
But I could not get it to work. I guess the only problem with this is, maven picks up the default level from the config file on the classpath. I also tried a couple of other settings via System.properties, but all of them were unsuccessful.
You can find the source of slf4j on github here : slf4j github
The source of the simplelogger here : slf4j/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/SimpleLog.java
The plexus loader loads the simplelogger.properties
.
You might also want to look at the subprocess
module, which was built to replace the whole family of Python popen
-type calls.
import subprocess
output = subprocess.check_output("cat /etc/services", shell=True)
The advantage it has is that there is a ton of flexibility with how you invoke commands, where the standard in/out/error streams are connected, etc.
You use a forward declaration when you need a complete type.
You must have a full definition of the class in order to use it.
The usual way to go about this is:
1) create a file Cat_main.h
2) move
#include <string>
class Cat
{
public:
Cat(std::string str);
// Variables
std::string name;
// Functions
void Meow();
};
to Cat_main.h
. Note that inside the header I removed using namespace std;
and qualified string with std::string
.
3) include this file in both Cat_main.cpp
and Cat.cpp
:
#include "Cat_main.h"
The API docs on link_to show some examples of adding querystrings to both named and oldstyle routes. Is this what you want?
link_to
can also produce links with anchors or query strings:
link_to "Comment wall", profile_path(@profile, :anchor => "wall")
#=> <a href="/profiles/1#wall">Comment wall</a>
link_to "Ruby on Rails search", :controller => "searches", :query => "ruby on rails"
#=> <a href="/searches?query=ruby+on+rails">Ruby on Rails search</a>
link_to "Nonsense search", searches_path(:foo => "bar", :baz => "quux")
#=> <a href="/searches?foo=bar&baz=quux">Nonsense search</a>
At least with gcc 5.4 virtual functions could be template members but has to be templates themselves.
#include <iostream>
#include <string>
class first {
protected:
virtual std::string a1() { return "a1"; }
virtual std::string mixt() { return a1(); }
};
class last {
protected:
virtual std::string a2() { return "a2"; }
};
template<class T> class mix: first , T {
public:
virtual std::string mixt() override;
};
template<class T> std::string mix<T>::mixt() {
return a1()+" before "+T::a2();
}
class mix2: public mix<last> {
virtual std::string a1() override { return "mix"; }
};
int main() {
std::cout << mix2().mixt();
return 0;
}
Outputs
mix before a2
Process finished with exit code 0
You could insert both the key,value pair and its inverse into your map structure, but would have to convert the Integer to a string:
map.put("theKey", "theValue");
map.put("theValue", "theKey");
Using map.get("theValue") will then return "theKey".
It's a quick and dirty way that I've made constant maps, which will only work for a select few datasets:
If you want to keep <Integer, String>
you could maintain a second <String, Integer>
map to "put" the value -> key pairs.
A safer way to approach breaking a foreach
or while
loop in PHP is to nest an incrementing counter variable and if
conditional inside of the original loop. This gives you tighter control than break;
which can cause havoc elsewhere on a complicated page.
Example:
// Setup a counter
$ImageCounter = 0;
// Increment through repeater fields
while ( condition ):
$ImageCounter++;
// Only print the first while instance
if ($ImageCounter == 1) {
echo 'It worked just once';
}
// Close while statement
endwhile;
Use [ngClass]
and conditionally apply class based on the id
.
In your HTML file:
<li>
<img [ngClass]="{'this-is-a-class': id === 1 }" id="1"
src="../../assets/images/1.jpg" (click)="addClass(id=1)"/>
</li>
<li>
<img [ngClass]="{'this-is-a-class': id === 2 }" id="2"
src="../../assets/images/2.png" (click)="addClass(id=2)"/>
</li>
In your TypeScript file:
addClass(id: any) {
this.id = id;
}
To remove a timezone (tzinfo) from a datetime object:
# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)
If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.
# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)
Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime
object to insert into the database. The solution is to convert your datetime.datetime
object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime
objects where one is timezone aware and another is timezone naive.
##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
arrowDt = arrowObj.to("utc").datetime
# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)
# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()
# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3
# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True
Simple function. Transform strings like 'Ábç Éfg' to 'abc_efg'
/**
* @param $str
* @return mixed
*/
function sanitizeString($str) {
$str = preg_replace('/[áàãâä]/ui', 'a', $str);
$str = preg_replace('/[éèêë]/ui', 'e', $str);
$str = preg_replace('/[íìîï]/ui', 'i', $str);
$str = preg_replace('/[óòõôö]/ui', 'o', $str);
$str = preg_replace('/[úùûü]/ui', 'u', $str);
$str = preg_replace('/[ç]/ui', 'c', $str);
$str = preg_replace('/[^a-z0-9]/i', '_', $str);
$str = preg_replace('/_+/', '_', $str);
return $str;
}
Thanks to Andrey Egorov, in my case with python setAttribute
not working, but I found I can set the property directly,
Try this code:
driver.execute_script("document.getElementById('q').value='value here'")
I had the same problem when running:
dotnet ef migrations add InitialCreate
so what I did is tried to build the project using:
dotnet build
command.
It throws an error : Startup.cs(20,27): error CS0103: bla bla
for example. which you can trace to find the error in your code.
Then i refactored the code and ran:
dotnet build
again
to check any errors until there is no errors and build is succeded.
Then ran:
dotnet ef migrations add InitialCreate
then the build succeded.
Maybe it's possible to debug PHP on Visual Studio, but it's simpler and more logical to use Eclipse PDT or Netbeans IDE for your PHP projects, aside from Visual Studio if you need to use both technologies from two different vendors.
server.servlet.context-path=/api
would be the solution I guess. I had the same issue and this got me solved. I used server.context-path. However, that seemed to be deprecated and I found that server.servlet.context-path
solves the issue now. Another workaround I found was adding a base tag to my front end (H5) pages. I hope this helps someone out there.
Cheers
Create below class in base class. Class To get all controls:
public static class ControlExtensions
{
public static IEnumerable<T> GetAllControlsOfType<T>(this Control parent) where T : Control
{
var result = new List<T>();
foreach (Control control in parent.Controls)
{
if (control is T)
{
result.Add((T)control);
}
if (control.HasControls())
{
result.AddRange(control.GetAllControlsOfType<T>());
}
}
return result;
}
}
From Database: Get All Actions IDs (like divAction1,divAction2 ....) dynamic in DATASET (DTActions) allow on specific User.
In Aspx: in HTML Put Action(button,anchor etc) in div or span and give them id like
<div id="divAction1" visible="false" runat="server" clientidmode="Static">
<a id="anchorAction" runat="server">Submit
</a>
</div>
IN CS: Use this function on your page:
private void ShowHideActions()
{
var controls = Page.GetAllControlsOfType<HtmlGenericControl>();
foreach (DataRow dr in DTActions.Rows)
{
foreach (Control cont in controls)
{
if (cont.ClientID == "divAction" + dr["ActionID"].ToString())
{
cont.Visible = true;
}
}
}
}
Pidfile contains pid of a process. It is a convention allowing long running processes to be more self-aware. Server process can inspect it to stop itself, or have heuristic that its other instance is already running. Pidfiles can also be used to conventiently kill risk manually, e.g. pkill -F <some.pid>
Did you try
$(this).val('test');
instead of
$(this).attr('value', 'test');
val()
is generally easier, since the attribute you need to change may be different on different DOM elements.
For example:
String myInput = null;
Scanner myscan = new Scanner(System.in).useDelimiter("\\n");
System.out.println("Enter your input: ");
myInput = myscan.next();
System.out.println(myInput);
This will let you use Enter as a delimiter.
Thus, if you input:
Hello world (ENTER)
it will print 'Hello World'.
var i = 0;_x000D_
var length = 10;_x000D_
_x000D_
function for1() {_x000D_
console.log(i);_x000D_
for2();_x000D_
}_x000D_
_x000D_
function for2() {_x000D_
if (i == length) {_x000D_
return false;_x000D_
}_x000D_
setTimeout(function() {_x000D_
i++;_x000D_
for1();_x000D_
}, 500);_x000D_
}_x000D_
for1();
_x000D_
Here is a sample functional approach to what is expected here.
select * from Tran_LibraryBooksTrans LBT left join
Tran_LibraryIssuedBooks LIB ON case WHEN LBT.IssuedTo='SN' AND
LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1 when LBT.IssuedTo='SM'
AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1 WHEN
LBT.IssuedTo='BO' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1
ELSE 0 END`enter code here`select * from Tran_LibraryBooksTrans LBT
left join Tran_LibraryIssuedBooks LIB ON case WHEN LBT.IssuedTo='SN'
AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1 when
LBT.IssuedTo='SM' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1
WHEN LBT.IssuedTo='BO' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN
1 ELSE 0 END
Root-gradle file:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:x.x.x'
}
}
allprojects {
repositories {
jcenter()
}
}
Gradle-wrapper.properties file:
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-x.x-all.zip
Depends on what you need, you have a couple of choices, you can do:
// this will replace the first occurrence of "www." and return "testwww.com"
"www.testwww.com".replace("www.", "");
// this will slice the first four characters and return "testwww.com"
"www.testwww.com".slice(4);
// this will replace the www. only if it is at the beginning
"www.testwww.com".replace(/^(www\.)/,"");
Copy file using Square's Okio:
BufferedSink bufferedSink = Okio.buffer(Okio.sink(destinationFile));
bufferedSink.writeAll(Okio.source(sourceFile));
bufferedSink.close();
complete.cases
gives TRUE
when all values in a row are not NA
DF[!complete.cases(DF), ]
Sudo is a Unix specific command designed to allow a user to carry out administrative tasks with the appropriate permissions.
Windows does not have (need?) this.
Run the command with the sudo removed from the start.
https://www.programmableweb.com/ -- Great collection of all category API's across web. It not only show cases the API's , but also Developers who use those API's in their applications and code samples, rating of the API and much more. They have more than apis they also have sdk and libraries too.
The <span>
tag will need to be set to display:block
as it is an inline element and will ignore width.
so:
<style type="text/css"> span { width: 50px; display: block; } </style>
and then:
<li><span> </span>something</li>
<li><span>AND</span>something else</li>
Ya'll are making it too complicated.
Just use plain php
<?php $i = 1; ?>
{{$i}}
donesies.
(or https://github.com/alexdover/blade-set looks pretty straighforward too)
We're all kinda "hacking" the system by setting variables in views, so why make the "hack" more complicated then it needs to be?
Tested in Laravel 4.
Another benefit is that syntax highlighting works properly (I was using comment hack before and it was awful to read)
Comparaison of the different methods:
> CGI::escapeHTML("quote ' double quotes \"")
=> "quote ' double quotes ""
> Rack::Utils.escape_html("quote ' double quotes \"")
=> "quote ' double quotes ""
> ERB::Util.html_escape("quote ' double quotes \"")
=> "quote ' double quotes ""
I wrote my own to be compatible with Rails ActiveMailer escaping:
def escape_html(str)
CGI.escapeHTML(str).gsub("'", "'")
end
You could also try the Visual Studio Android Emulator, which can also be installed as a standalone emulator (you don't need Visual Studio). Please note, that it can be installed only on Windows Pro or higher systems.
You entered an alphanumeric and int, blank delimited in mystr
.
You then tried to convert the first token (blank delimited) into an int
.
The first token was RS which failed to convert to int
, leaving a zero for myprice, and we all know what zero times anything yields.
When you only entered int values the second time, everything worked as you expected.
It was the spurious RS that caused your code to fail.
The X-Content-Type-Options response HTTP header is a marker used by the server to indicate that the MIME types advertised in the Content-Type headers should not be changed and be followed. This allows to opt-out of MIME type sniffing, or, in other words, it is a way to say that the webmasters knew what they were doing.
Syntax :
X-Content-Type-Options: nosniff
Directives :
nosniff Blocks a request if the requested type is 1. "style" and the MIME type is not "text/css", or 2. "script" and the MIME type is not a JavaScript MIME type.
Note: nosniff only applies to "script" and "style" types. Also applying nosniff to images turned out to be incompatible with existing web sites.
Specification :
https://fetch.spec.whatwg.org/#x-content-type-options-header
When you use the following (without disable-output-escaping
!) you'll get a single non-breaking space:
<xsl:text> </xsl:text>
This will work:
select * into DestinationDatabase.dbo.[TableName1] from (
Select * from sourceDatabase.dbo.[TableName1])Temp
From my own experience , there are two way:
use ipdb,which is a enhanced debugger likes pdb.
import ipdb;ipdb.set_trace()
or breakpoint()
(from python3.7)
use django shell ,just use the command below. This is very helpfull when you are developing a new view.
python manage.py shell
ls | xargs -I % mv % %_`date +%d%b%Y`
One line is enough. ls all files/dirs under current dir and append date to each file.
The most up-to-date answer to this is: they are listed under the 'Network' button in the developer tools, no longer under 'Resources' like it used to be.
Function errors are a common thing in almost all content management systems and there is a few ways you can approach this.
Wrap your code using:
<script>
jQuery(function($) {
YOUR CODE GOES HERE
});
</script>
You can also use jQuery's API using noConflict();
<script>
$.noConflict();
jQuery( document ).ready(function( $ ) {
// Code that uses jQuery's $ can follow here.
});
// Code that uses other library's $ can follow here.
</script>
Another example of using noConflict without using document ready:
<script>
jQuery.noConflict();
(function( $ ) {
$(function() {
// YOUR CODE HERE
});
});
</script>
You could even choose to create your very alias to avoid conflicts like so:
var jExample = jQuery.noConflict();
// Do something with jQuery
jExample( "div p" ).hide();
Yet another longer solution is to rename all referances of $ to jQuery:
$( "div p" ).hide();
to jQuery( "div p" ).hide();
Fixed it by setting the class name to the property "classesToBeBound" of the JAXB marshaller:
<bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>myclass</value>
</list>
</property>
</bean>
try: var cc = @Html.Raw(Json.Encode(ViewBag.CC)
You can JOIN with the same table more than once by giving the joined tables an alias, as in the following example:
SELECT
airline, flt_no, fairport, tairport, depart, arrive, fare
FROM
flights
INNER JOIN
airports from_port ON (from_port.code = flights.fairport)
INNER JOIN
airports to_port ON (to_port.code = flights.tairport)
WHERE
from_port.code = '?' OR to_port.code = '?' OR airports.city='?'
Note that the to_port
and from_port
are aliases for the first and second copies of the airports
table.
python 2.7
import pymysql
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='password', db='sakila')
cur = conn.cursor()
n = cur.execute('select * from actor')
c = cur.fetchall()
for i in c:
print i[1]
I solved this question this way.
<a class="btn btn-primary" target="_blank" ng-href="{{url}}" ng-mousedown="openTab()">newTab</a>
$scope.openTab = function() {
$scope.url = 'www.google.com';
}
Two things are happening here.
Bootstrap uses a grid system and the .container class is defined in its own CSS. The grid has to exist within a container class DIV. The container DIV is just an indication to Bootstrap that the grid within has that parent. Therefore, you cannot set the height of a container.
What you want to do is the following:
<div class="container-fluid"> <!-- this is to make it responsive to your screen width -->
<div class="row">
<div class="col-md-4 myClassName"> <!-- myClassName is defined in my CSS as you defined your container -->
<img src="#.jpg" height="200px" width="300px">
</div>
</div>
</div>
Here you can find more info on the Bootstrap grid system.
That being said, if you absolutely MUST override the Bootstrap CSS then I would try using the "!important" clause to my CSS definition as such...
.container {
padding-right: 15px;
padding-left: 15px;
margin-right: auto;
margin-left: auto;
max-width: 900px;
overflow:hidden;
min-height:0px !important;
}
But I have always found that the "!important" clause just makes for messy CSS.
Following up on @Bruno Bronosky and @mrteatime, I offer the suggestion that you just write your boolean return "backwards". This is what I mean:
foo()
{
if [ "$1" == "bar" ]; then
true; return
else
false; return
fi;
}
That eliminates the ugly two line requirement for every return statement.