Since glibc version 2.17, the library linking -lrt
is no longer required.
The clock_*
are now part of the main C library. You can see the change history of glibc 2.17 where this change was done explains the reason for this change:
+* The `clock_*' suite of functions (declared in <time.h>) is now available
+ directly in the main C library. Previously it was necessary to link with
+ -lrt to use these functions. This change has the effect that a
+ single-threaded program that uses a function such as `clock_gettime' (and
+ is not linked with -lrt) will no longer implicitly load the pthreads
+ library at runtime and so will not suffer the overheads associated with
+ multi-thread support in other code such as the C++ runtime library.
If you decide to upgrade glibc, then you can check the compatibility tracker of glibc if you are concerned whether there would be any issues using the newer glibc.
To check the glibc version installed on the system, run the command:
ldd --version
(Of course, if you are using old glibc (<2.17) then you will still need -lrt
.)
quick answer
#include<stdio.h>
#include<time.h>
int main()
{
clock_t t1, t2;
t1 = clock();
int i;
for(i = 0; i < 1000000; i++)
{
int x = 90;
}
t2 = clock();
float diff = ((float)(t2 - t1) / 1000000.0F ) * 1000;
printf("%f",diff);
return 0;
}
Example how to run program and write stdout and stderr to file with timestamp:
cmd /c ""C:\Program Files (x86)\program.exe" -param fooo >> "c:\dir space\Log_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt" 2>&1"
Key part is to double quote whole part behind cmd /c
and inside it use double quotes as usual. Also note that date is locale dependent, this example works using US locale.
This is a method that I use to update AppSettings, works for both web and desktop applications. If you need to edit connectionStrings you can get that value from System.Configuration.ConnectionStringSettings config = configFile.ConnectionStrings.ConnectionStrings["YourConnectionStringName"];
and then set a new value with config.ConnectionString = "your connection string";
. Note that if you have any comments in the connectionStrings
section in Web.Config
these will be removed.
private void UpdateAppSettings(string key, string value)
{
System.Configuration.Configuration configFile = null;
if (System.Web.HttpContext.Current != null)
{
configFile =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
}
else
{
configFile =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
}
var settings = configFile.AppSettings.Settings;
if (settings[key] == null)
{
settings.Add(key, value);
}
else
{
settings[key].Value = value;
}
configFile.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
}
I have too low reputation to add comment to @bernie response, with response to @user1506145. I have run in to same issue.
The answer to it is a interval parameter which fixes things up
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import datetime as dt
np.random.seed(1)
N = 100
y = np.random.rand(N)
now = dt.datetime.now()
then = now + dt.timedelta(days=100)
days = mdates.drange(now,then,dt.timedelta(days=1))
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=5))
plt.plot(days,y)
plt.gcf().autofmt_xdate()
plt.show()
Sure, that is why python implements the following methods where the first parameter is a function:
IF "%1"=="" will fail, all versions of this will fail under certain poison character conditions. Only IF DEFINED or IF NOT DEFINED are safe
pd.set_option('display.max_rows', 500)
df
Does not work in Jupyter!
Instead use:
pd.set_option('display.max_rows', 500)
df.head(500)
The android.arch.lifecycle package provides classes and interfaces that let you build lifecycle-aware components
Your application should implement the LifecycleObserver interface:
public class MyApplication extends Application implements LifecycleObserver {
@Override
public void onCreate() {
super.onCreate();
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
private void onAppBackgrounded() {
Log.d("MyApp", "App in background");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
private void onAppForegrounded() {
Log.d("MyApp", "App in foreground");
}
}
To do that, you need to add this dependency to your build.gradle file:
dependencies {
implementation "android.arch.lifecycle:extensions:1.1.1"
}
As recommended by Google, you should minimize the code executed in the lifecycle methods of activities:
A common pattern is to implement the actions of the dependent components in the lifecycle methods of activities and fragments. However, this pattern leads to a poor organization of the code and to the proliferation of errors. By using lifecycle-aware components, you can move the code of dependent components out of the lifecycle methods and into the components themselves.
You can read more here: https://developer.android.com/topic/libraries/architecture/lifecycle
You state in the comments that the returned JSON is this:
{
"dstOffset" : 3600,
"rawOffset" : 36000,
"status" : "OK",
"timeZoneId" : "Australia/Hobart",
"timeZoneName" : "Australian Eastern Daylight Time"
}
You're telling Gson that you have an array of Post
objects:
List<Post> postsList = Arrays.asList(gson.fromJson(reader,
Post[].class));
You don't. The JSON represents exactly one Post
object, and Gson is telling you that.
Change your code to be:
Post post = gson.fromJson(reader, Post.class);
__VA_ARGS__
is the standard way to do it. Don't use compiler-specific hacks if you don't have to.
I'm really annoyed that I can't comment on the original post. In any case, C++ is not a superset of C. It is really silly to compile your C code with a C++ compiler. Don't do what Donny Don't does.
One could think that xlsb has only advantages over xlsm. The fact that xlsm is XML-based and xlsb is binary is that when workbook corruption occurs, you have better chances to repair a xlsm than a xlsb.
This can also be done as follows. Put your commands in a script, let's name it commands-inc.sh
#!/bin/bash
ls some_folder
./someaction.sh
pwd
Save the file
Now run it on the remote server.
ssh user@remote 'bash -s' < /path/to/commands-inc.sh
Never failed for me.
I use:
used_features =[
"one",
"two",
"three"
]
df['is_duplicated'] = df.duplicated(used_features)
df['is_duplicated'].sum()
which gives count of duplicated rows, and then you can analyse them by a new column. I didn't see such solution here.
HTML :
<div id="myDiv">
<form id="myForm">
</form>
</div>
jQuery :
var chbx='<input type="checkbox" id="Mumbai" name="Mumbai" value="Mumbai" />Mumbai<br /> <input type="checkbox" id=" Delhi" name=" Delhi" value=" Delhi" /> Delhi<br/><input type="checkbox" id=" Bangalore" name=" Bangalore" value=" Bangalore"/>Bangalore<br />';
$("#myDiv form#myForm").html(chbx);
//to insert dynamically created form
$("#myDiv").html("<form id='dynamicForm'>" +chbx + "'</form>");
Here is another possible solution assuming matrix have one column( you can reshape original Mat to one column Mat via reshape):
Mat matrix= Mat::zeros(20, 1, CV_32FC1);
vector<float> vec;
matrix.col(0).copyTo(vec);
Steps:
1 - Right click on your task bar -->Start Task Manager
2 - Click on Services button (at bottom).
3 - Search for MYSQL57
4 - Right Click on MYSQL57 --> Start
Now again start your mysql-cmd-prompt or MYSQL WorkBench
I had the same problem. I fixed it using the command below:
git checkout main
git fetch
git checkout branch_name
git fetch
git checkout main
git fetch
git merge branch_name
Here's a function that can include an optional offset for those fixed headers. No external libraries needed.
function scrollIntoView(selector, offset = 0) {
window.scroll(0, document.querySelector(selector).offsetTop - offset);
}
You can grab the height of an element using JQuery and scroll to it.
var headerHeight = $('.navbar-fixed-top').height();
scrollIntoView('#some-element', headerHeight)
Update March 2018
Scroll to this answer without using JQuery
scrollIntoView('#answer-44786637', document.querySelector('.top-bar').offsetHeight)
just use the full url as href like this:
<a href="https://www.example.com/" target="_blank">page link</a>
Implement your own extension of DataGridViewTextBoxCell and override Paint method like this:
class MyDataGridViewTextBoxCell : DataGridViewTextBoxCell
{
protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex,
DataGridViewElementStates cellState, object value, object formattedValue, string errorText,
DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
{
if (value != null)
{
if ((bool) value)
{
cellStyle.BackColor = Color.LightGreen;
}
else
{
cellStyle.BackColor = Color.OrangeRed;
}
}
base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value,
formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
}
}
Then in the code set CellTemplate property of your column to instance of your class
columns.Add(new DataGridViewTextBoxColumn() {CellTemplate = new MyDataGridViewTextBoxCell()});
you can try this function for multi-purpose
function ManageData($table_name='',$condition=array(),$udata=array(),$is_insert=false){
$resultArr = array();
$ci = & get_instance();
if($condition && count($condition))
$ci->db->where($condition);
if($is_insert)
{
$ci->db->insert($table_name,$udata);
return 0;
}
else
{
$ci->db->update($table_name,$udata);
return 1;
}
}
You can simply do this:
Name.objects.exclude(alias="").exclude(alias=None)
It's really just that simple. filter
is used to match and exclude
is to match everything but what it specifies. This would evaluate into SQL as NOT alias='' AND alias IS NOT NULL
.
The real answer is you need to set the escape character to '\': SET ESCAPE ON
The problem may have occurred either because escaping was disabled, or the escape character was set to something other than '\'. The above statement will enable escaping and set it to '\'.
None of the other answers previously posted actually answer the original question. They all work around the problem but don't resolve it.
.model small
.stack 100h
.code
Main proc
Mov cx , 30 ; //that number control the loop 30 means the loop will
;excite 30 time
Ioopfront:
Mov ah , 1
Int 21h
Loop loopfront;
this cod will take 30 character
The OP says, for unknown reasons, "I prefer it without an arraylist or list."
If the type you are referring to is a primitive (you mention integers, but you don't say if you mean int
or Integer
), then you can use one of the NIO Buffer classes like java.nio.IntBuffer
. These act a lot like StringBuffer
does - they act as buffers for a list of the primitive type (buffers exist for all the primitives but not for Objects), and you can wrap a buffer around an array and/or extract an array from a buffer.
Note that the javadocs say, "The capacity of a buffer is never negative and never changes." It's still just a wrapper around an array, but one that's nicer to work with. The only way to effectively expand a buffer is to allocate()
a larger one and use put()
to dump the old buffer into the new one.
If it's not a primitive, you should probably just use List
, or come up with a compelling reason why you can't or won't, and maybe somebody will help you work around it.
Use pivot tables, it will definitely save you time. If you are using excel 2007+ use tables (structured references) to keep your table dynamic. However if you insist on using functions, go with Smandoli's suggestion. Again, if you are on 2007+ use SUMIFS, it's faster compared to SUMIF.
Working from VaLo's answer:
cd %directory to browser%
%browser's name to main executable (firefox, chrome, opera, etc.)% https://www.google.com
start https://www.google.com
doesn't seem to work (at least in my environment)
You can do this with the additional effects in jQuery UI: See here for details
Quick example:
$(this).hide("slide", { direction: "left" }, 1000);
$(this).show("slide", { direction: "left" }, 1000);
An example statement that uses a sub-select :
select * into MyNewTable
from
(
select
*
from
[SomeOtherTablename]
where
EventStartDatetime >= '01/JAN/2018'
)
) mysourcedata
;
note that the sub query must be given a name .. any name .. e.g. above example gives the subquery a name of mysourcedata. Without this a syntax error is issued in SQL*server 2012.
The database should reply with a message like: (9999 row(s) affected)
this sorting funciton can be use for all object sorting,
object
deepObject
you can also do assending or desending sort by passing 1,-1 as param
Object.defineProperty(Object.prototype, 'deepVal', {_x000D_
enumerable: false,_x000D_
writable: true,_x000D_
value: function (propertyChain) {_x000D_
var levels = propertyChain.split('.');_x000D_
parent = this;_x000D_
for (var i = 0; i < levels.length; i++) {_x000D_
if (!parent[levels[i]])_x000D_
return undefined;_x000D_
parent = parent[levels[i]];_x000D_
}_x000D_
return parent;_x000D_
}_x000D_
});_x000D_
_x000D_
_x000D_
function dynamicSortAll(property,sortOrders=1) {_x000D_
_x000D_
/**default sorting will be ascending order if you need descending order_x000D_
sording you have to pass -1 as param**/_x000D_
_x000D_
var sortOrder = sortOrders;_x000D_
_x000D_
return function (a,b) {_x000D_
_x000D_
var result =(property? ((a.deepVal(property) > b.deepVal(property)) ? 1 : (a.deepVal(property) < b.deepVal(property)) ? -1 : 0) :((a > b) ? 1 : (a < b) ? -1 : 0))_x000D_
_x000D_
return result * sortOrder;_x000D_
_x000D_
_x000D_
}_x000D_
}_x000D_
_x000D_
deepObj = [_x000D_
{_x000D_
a: { a: 1, b: 2, c: 3 },_x000D_
b: { a: 4, b: 5, c: 6 }_x000D_
},_x000D_
{ _x000D_
a: { a: 3, b: 2, c: 1 },_x000D_
b: { a: 6, b: 5, c: 4 }_x000D_
}];_x000D_
_x000D_
let deepobjResult=deepObj.sort(dynamicSortAll('a.a',1))_x000D_
console.log('deepobjResult :'+ JSON.stringify(deepobjResult))_x000D_
var obj = [ _x000D_
{ first_nom: 'Lazslo', last_nom: 'Jamf' },_x000D_
{ first_nom: 'Pig', last_nom: 'Bodine' },_x000D_
{ first_nom: 'Pirate', last_nom: 'Prentice' }_x000D_
];_x000D_
let objResult=obj.sort(dynamicSortAll('last_nom',1))_x000D_
console.log('objResult :'+ JSON.stringify(objResult))_x000D_
_x000D_
var numericObj=[1,2,3,4,5,6]_x000D_
_x000D_
let numResult=numericObj.sort(dynamicSortAll(null,-1))_x000D_
console.log('numResult :'+ JSON.stringify(numResult))_x000D_
_x000D_
let stringSortResult='helloworld'.split('').sort(dynamicSortAll(null,1))_x000D_
_x000D_
console.log('stringSortResult:'+ JSON.stringify(stringSortResult))_x000D_
_x000D_
let uniqueStringOrger=[...new Set(stringSortResult)]; _x000D_
console.log('uniqueStringOrger:'+ JSON.stringify(uniqueStringOrger))
_x000D_
In theory, yes, it's just a matter of plugging things in. Zipfile can give you a file-like object for a file in a zip archive, and image.load will accept a file-like object. So something like this should work:
import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
try:
image = pygame.image.load(imgfile, 'img_01.png')
finally:
imgfile.close()
I've found this way to create dataframe by raw without matrix.
With automatic column name
df<-data.frame(
t(data.frame(c(1,"a",100),c(2,"b",200),c(3,"c",300)))
,row.names = NULL,stringsAsFactors = FALSE
)
With column name
df<-setNames(
data.frame(
t(data.frame(c(1,"a",100),c(2,"b",200),c(3,"c",300)))
,row.names = NULL,stringsAsFactors = FALSE
),
c("col1","col2","col3")
)
It was used for "intermediate materialization (Google search)"
Good article: Adam Machanic: Exploring the secrets of intermediate materialization
He even raised an MS Connect so it can be done in a cleaner fashion
My view is "not inherently bad", but don't use it unless 100% sure. The problem is, it works only at the time you do it and probably not later (patch level, schema, index, row counts etc)...
This may fail because you don't know in which order things are evaluated
SELECT foo From MyTable WHERE ISNUMERIC (foo) = 1 AND CAST(foo AS int) > 100
And this may also fail because
SELECT foo
FROM
(SELECT foo From MyTable WHERE ISNUMERIC (foo) = 1) bar
WHERE
CAST(foo AS int) > 100
However, this did not in SQL Server 2000. The inner query is evaluated and spooled:
SELECT foo
FROM
(SELECT TOP 100 PERCENT foo From MyTable WHERE ISNUMERIC (foo) = 1 ORDER BY foo) bar
WHERE
CAST(foo AS int) > 100
Note, this still works in SQL Server 2005
SELECT TOP 2000000000 ... ORDER BY...
For PDO You may do this
$stmt1 = "INSERT INTO users (username, password) VALUES('test', 'test')";
$stmt2 = "INSERT INTO profiles (userid, bio, homepage) VALUES('LAST_INSERT_ID(),'Hello world!', 'http://www.stackoverflow.com')";
$sth1 = $dbh->prepare($stmt1);
$sth2 = $dbh->prepare($stmt2);
BEGIN;
$sth1->execute (array ('test','test'));
$sth2->execute (array ('Hello world!','http://www.stackoverflow.com'));
COMMIT;
Use System.IO.File.ReadAllText(fileName)
The copy buffer can't be accessed outside of nano, and nowhere I found any buffer file to read.
Here is a dirty alternative when in full NOX: Printing a given file line in the bash history.
So the given line is available as a command with the UP key.
sed "LINEq;d" FILENAME >> ~/.bash_history
Example:
sed "342q;d" doc.txt >> ~/.bash_history
Then to reload the history into the current session:
history -n
Or to make history reloading automatic at new prompts, paste this in .bash_profile
:
PROMPT_COMMAND='history -n ; $PROMPT_COMMAND'
Note for AZERTY keyboards and very probably others layouts that require SHIFT for printing numbers from the top keys.
To toggle nano
text selection (Mark Set/Unset
) the shortcut is:
CTRL + SHIFT + 2
Or
ALT + a
You can then select the text with the arrows keys.
All of the others shortcuts works fine as the documentation:
CTRL + k or F9 to cut.
CTRL + u or F10 to paste.
It turns out that I needed to use gulp-rename
and also output the concatenated file first before 'uglification'. Here's the code:
var gulp = require('gulp'),
gp_concat = require('gulp-concat'),
gp_rename = require('gulp-rename'),
gp_uglify = require('gulp-uglify');
gulp.task('js-fef', function(){
return gulp.src(['file1.js', 'file2.js', 'file3.js'])
.pipe(gp_concat('concat.js'))
.pipe(gulp.dest('dist'))
.pipe(gp_rename('uglify.js'))
.pipe(gp_uglify())
.pipe(gulp.dest('dist'));
});
gulp.task('default', ['js-fef'], function(){});
Coming from grunt
it was a little confusing at first but it makes sense now. I hope it helps the gulp
noobs.
And, if you need sourcemaps, here's the updated code:
var gulp = require('gulp'),
gp_concat = require('gulp-concat'),
gp_rename = require('gulp-rename'),
gp_uglify = require('gulp-uglify'),
gp_sourcemaps = require('gulp-sourcemaps');
gulp.task('js-fef', function(){
return gulp.src(['file1.js', 'file2.js', 'file3.js'])
.pipe(gp_sourcemaps.init())
.pipe(gp_concat('concat.js'))
.pipe(gulp.dest('dist'))
.pipe(gp_rename('uglify.js'))
.pipe(gp_uglify())
.pipe(gp_sourcemaps.write('./'))
.pipe(gulp.dest('dist'));
});
gulp.task('default', ['js-fef'], function(){});
See gulp-sourcemaps for more on options and configuration.
:not
selector:
input:not([type]), input[type='text'], input[type='password'] {
/* style here */
}
Support: in Internet Explorer 9 and higher
You've got the right idea. Looks to me like you just need to change .tag
's position:relative
to position:absolute
, and add position:relative
to .container
.
If you are using Adobe Acrobat X to make the form, set all the fields as you want them, then click File, Save As, Reader Extended PDF, Enable Additional Features. The resulting PDF form can be saved when filled in, if opened in versions of Adobe Reader before XI.
I used the following code to apply some external CSS:
boxText = document.createElement("html");
boxText.innerHTML = "<head><link rel='stylesheet' href='style.css'/></head><body>[some html]<body>";
infowindow.setContent(boxText);
infowindow.open(map, marker);
This worked for me. :)
sudo keytool -importcert -file filename.cer -alias randomaliasname -keystore $JAVA_HOME/jre/lib/security/cacerts -storepass changeit
Swift 5
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
//Delete or comment the below lines on your SceneDelegate.
// guard let windowScene = (scene as? UIWindowScene) else { return }
// window?.windowScene = windowScene
// window?.makeKeyAndVisible()
let viewController = ListVC()
let navViewController = UINavigationController(rootViewController: viewController)
window?.rootViewController = navViewController
}
I through vnc to understand the X11 more. To specify the display to get a many-displayed program, export DISPLAY=IP:DisplayNum.ScreenNum
For example,
vncserver :2
vncserver -list
echo '$DISPLAY'=$DISPLAY
export DISPLAY=:2 # export DISPLAY=IP:DisplayNum or export DISPLAY=:DisplayNum for localhost; So that can vnc connect and see the vnc desktop :2 if $DISPLAY is not :2.
echo '$DISPLAY'=$DISPLAY
int[] getAdminIDList(String tableName, String attributeName, int value) throws SQLException {
ArrayList list = null;
Statement statement = conn.createStatement();
ResultSet result = statement.executeQuery("SELECT admin_id FROM " + tableName + " WHERE " + attributeName + "='" + value + "'");
while (result.next()) {
list.add(result.getInt(1));
}
statement.close();
int id[] = new int[list.size()];
for (int i = 0; i < id.length; i++) {
try {
id[i] = ((Integer) list.get(i)).intValue();
} catch(NullPointerException ne) {
} catch(ClassCastException ch) {}
}
return id;
}
// enter code here
This code shows why ArrayList
is important and why we use it. Simply casting int
from Object
. May be its helpful.
To answer your exact question you can get the exact behaviour you want by extending the Array prototype with:
Array.prototype.get = function(name) {
for (var i=0, len=this.length; i<len; i++) {
if (typeof this[i] != "object") continue;
if (this[i].name === name) return this[i].value;
}
};
this will add the get() method to all arrays and let you do what you want, i.e:
arr.get('k1'); //= abc
Nice answers. You could also set Jobs (i.e., commands) with "Crontab" for more flexibility (which provides different options to run scripts, loggin the outputs, etc.), although it requires more time to be understood and set properly:
Using '@reboot' you can Run a command once, at startup.
Wrapping up:
run $ sudo crontab -e -u root
And add a line at the end of the file with your command as follows:
@reboot sudo searchd
Double escaping is required when presented as a string.
Whenever I'm making a new regular expression I do a bunch of tests with online tools, for example: http://www.regexplanet.com/advanced/java/index.html
That website allows you to enter the regular expression, which it'll escape into a string for you, and you can then test it against different inputs.
If you are just getting into Android, you would be well served by using Android Studio rather than using any version of Eclipse. Android Studio was released in 2013 and provides a nice integrated development environment for developing for Android.
Android Studio is based on IntelliJ, which is a great java devlopment environment. It also has these specific Android features:
You can download it here.
Where you declare the myclass[] array as :
xClass myclass[] = new xClass[10]
, simply pass in as an argument the number of XClass elements you'll need. At that point do you know how many you will need? By declaring the array as having 10 elements, you are not declaring 10 XClass objects, you're simply creating an array with 10 elements of type xClass.
Just want to mention another option here.
You can compute the coefficients using numpy.polyfit(), and feed the coefficients to numpy.poly1d(). This function can construct polynomials using the coefficients, you can find more examples here
https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.poly1d.html
Let's say, given two data points (-0.3, -0.5) and (0.8, 0.8)
import numpy as np
import matplotlib.pyplot as plt
# compute coefficients
coefficients = np.polyfit([-0.3, 0.8], [-0.5, 0.8], 1)
# create a polynomial object with the coefficients
polynomial = np.poly1d(coefficients)
# for the line to extend beyond the two points,
# create the linespace using the min and max of the x_lim
# I'm using -1 and 1 here
x_axis = np.linspace(-1, 1)
# compute the y for each x using the polynomial
y_axis = polynomial(x_axis)
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 1, 1])
axes.set_xlim(-1, 1)
axes.set_ylim(-1, 1)
axes.plot(x_axis, y_axis)
axes.plot(-0.3, -0.5, 0.8, 0.8, marker='o', color='red')
Hope it helps.
If you want this in config, you can set npm config like so:
npm config set prefix "$(pwd)/vendor/node_modules"
or
npm config set prefix "$HOME/vendor/node_modules"
Check your config with
npm config ls -l
Or as @pje says and use the --prefix
flag
'pywin32' is its canonical name.
Simple code for dynamic array. In below code then array will become full of size we copy all element to new double size array(variable size array).sample code is below
public class DynamicArray {
static int []increaseSizeOfArray(int []arr){
int []brr=new int[(arr.length*2)];
for (int i = 0; i < arr.length; i++) {
brr[i]=arr[i];
}
return brr;
}
public static void main(String[] args) {
int []arr=new int[5];
for (int i = 0; i < 11; i++) {
if (i<arr.length) {
arr[i]=i+100;
}
else {
arr=increaseSizeOfArray(arr);
arr[i]=i+100;
}
}
for (int i = 0; i < arr.length; i++) {
System.out.println("arr="+arr[i]);
}
}
}
Source : How to make dynamic array
For Laravel 5 you can use the Request object. Just call its ip()
method, something like:
$request->ip();
When I instantiate a promise, I'm going to generate an asynchronous function. If the function goes well then I call the RESOLVE then the flow continues in the RESOLVE handler, in the THEN. If the function fails, then terminate the function by calling REJECT then the flow continues in the CATCH.
In NodeJs are deprecated the rejection handler. Your error is just a warning and I read it inside node.js github. I found this.
DEP0018: Unhandled promise rejections
Type: Runtime
Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Date#parse
is deprecated . The alternative is :
java.text.DateFormat#parse
thereFore :
new SimpleDateFormat("E MMM dd H:m:s z yyyy", Locale.ARABIC).parse(testDate)
The problem with taking IEnumerable
as a parameter is that it tells callers "I wish to enumerate this". It doesn't tell them how many times you wish to enumerate.
I can change the objects parameter to be List and then avoid the possible multiple enumeration but then I don't get the highest object that I can handle.
The goal of taking the highest object is noble, but it leaves room for too many assumptions. Do you really want someone to pass a LINQ to SQL query to this method, only for you to enumerate it twice (getting potentially different results each time?)
The semantic missing here is that a caller, who perhaps doesn't take time to read the details of the method, may assume you only iterate once - so they pass you an expensive object. Your method signature doesn't indicate either way.
By changing the method signature to IList
/ICollection
, you will at least make it clearer to the caller what your expectations are, and they can avoid costly mistakes.
Otherwise, most developers looking at the method might assume you only iterate once. If taking an IEnumerable
is so important, you should consider doing the .ToList()
at the start of the method.
It's a shame .NET doesn't have an interface that is IEnumerable + Count + Indexer, without Add/Remove etc. methods, which is what I suspect would solve this problem.
A lot of these answers are pretty old, so I thought I would update with a solution that I think is helpful.
Our issue was similar to OP's, we upgraded 32 bit XP machines to 64 bit windows 7 and our application software that uses a 32 bit ODBC driver stopped being able to write to our database.
Turns out, there are two ODBC Data Source Managers, one for 32 bit and one for 64 bit. So I had to run the 32 bit version which is found in C:\Windows\SysWOW64\odbcad32.exe. Inside the ODBC Data Source Manager, I was able to go to the System DSN tab and Add my driver to the list using the Add button. (You can check the Drivers tab to see a list of the drivers you can add, if your driver isn't in this list then you may need to install it).
The next issue was the software that we ran was compiled to use 'Any CPU'. This would see the operating system was 64 bit, so it would look at the 64 bit ODBC Data Sources. So I had to force the program to compile as an x86 program, which then tells it to look at the 32 bit ODBC Data Sources. To set your program to x86, in Visual Studio go to your project properties and under the build tab at the top there is a platform drop down list, and choose x86. If you don't have the source code and can't compile the program as x86, you might be able to right click the program .exe and go to the compatibility tab and choose a compatibility that works for you.
Once I had the drivers added and the program pointing to the right drivers, everything worked like it use to. Hopefully this helps anyone working with older software.
It's works for me
git config --global receive.denyCurrentBranch updateInstead
git push origin master
Turns out there is a shutdown, but this must be initiated from another thread.
This solution worked for me: https://stackoverflow.com/a/22533929/573216
After installing redis
, type from terminal
:
redis-server
And Redis-Server will be started
There are a several ways of declaring variables in SQL*Plus scripts.
The first is to use VAR, to declare a bind variable. The mechanism for assigning values to a VAR is with an EXEC call:
SQL> var name varchar2(20)
SQL> exec :name := 'SALES'
PL/SQL procedure successfully completed.
SQL> select * from dept
2 where dname = :name
3 /
DEPTNO DNAME LOC
---------- -------------- -------------
30 SALES CHICAGO
SQL>
A VAR is particularly useful when we want to call a stored procedure which has OUT parameters or a function.
Alternatively we can use substitution variables. These are good for interactive mode:
SQL> accept p_dno prompt "Please enter Department number: " default 10
Please enter Department number: 20
SQL> select ename, sal
2 from emp
3 where deptno = &p_dno
4 /
old 3: where deptno = &p_dno
new 3: where deptno = 20
ENAME SAL
---------- ----------
CLARKE 800
ROBERTSON 2975
RIGBY 3000
KULASH 1100
GASPAROTTO 3000
SQL>
When we're writing a script which calls other scripts it can be useful to DEFine the variables upfront. This snippet runs without prompting me to enter a value:
SQL> def p_dno = 40
SQL> select ename, sal
2 from emp
3 where deptno = &p_dno
4 /
old 3: where deptno = &p_dno
new 3: where deptno = 40
no rows selected
SQL>
Finally there's the anonymous PL/SQL block. As you see, we can still assign values to declared variables interactively:
SQL> set serveroutput on size unlimited
SQL> declare
2 n pls_integer;
3 l_sal number := 3500;
4 l_dno number := &dno;
5 begin
6 select count(*)
7 into n
8 from emp
9 where sal > l_sal
10 and deptno = l_dno;
11 dbms_output.put_line('top earners = '||to_char(n));
12 end;
13 /
Enter value for dno: 10
old 4: l_dno number := &dno;
new 4: l_dno number := 10;
top earners = 1
PL/SQL procedure successfully completed.
SQL>
First you retreieve the value (given a key) and then you add a new element to it
ArrayList<String> grades = examList.get(courseId);
grades.add(aGrade);
To get JSON quickly into Java objects (Maps) that you can then 'drill' and work with, you can use json-io (https://github.com/jdereg/json-io). This library will let you read in a JSON String, and get back a 'Map of Maps' representation.
If you have the corresponding Java classes in your JVM, you can read the JSON in and it will parse it directly into instances of the Java classes.
JsonReader.jsonToMaps(String json)
where json is the String containing the JSON to be read. The return value is a Map where the keys will contain the JSON fields, and the values will contain the associated values.
JsonReader.jsonToJava(String json)
will read the same JSON string in, and the return value will be the Java instance that was serialized into the JSON. Use this API if you have the classes in your JVM that were written by
JsonWriter.objectToJson(MyClass foo).
Like this
png('filename.png')
# make plot
dev.off()
or this
# sometimes plots do better in vector graphics
svg('filename.svg')
# make plot
dev.off()
or this
pdf('filename.pdf')
# make plot
dev.off()
And probably others too. They're all listed together in the help pages.
If it helps someone you can just use css property
text-decoration-color: red;
JSONArray jArray = new JSONArray();
jArray.remove(position); // For remove JSONArrayElement
Note :- If remove()
isn't there in JSONArray
then...
API 19 from Android (4.4) actually allows this method.
Call requires API level 19 (current min is 16): org.json.JSONArray#remove
Right Click on Project Go to Properties
Select Android from left site option
And select Project Build Target greater then API 19
Hope it helps you.
image.setLayoutParams(new ViewGroup.LayoutParams(width, height));
example:
image.setLayoutParams(new ViewGroup.LayoutParams(150, 150));
For normal inlined <code>
use:
<code>...</code>
and for each and every place where blocked <code>
is needed use
<code style="display:block; white-space:pre-wrap">...</code>
Alternatively, define a <codenza>
tag for break lining block <code>
(no classes)
<script>
</script>
<style>
codenza, code {} /* noop mnemonic aide that codenza mimes code tag */
codenza {display:block;white-space:pre-wrap}
</style>`
Testing:
(NB: the following is a scURIple utilizing a data:
URI protocol/scheme, therefore the %0A
nl format codes are essential in preserving such when cut and pasted into the URL bar for testing - so view-source:
(ctrl-U) looks good preceed every line below with %0A
)
data:text/html;charset=utf-8,<html >
<script>document.write(window.navigator.userAgent)</script>
<script></script>
<style>
codenza, code {} /* noop mnemonic aide that codenza mimes code tag */
codenza {display:block;white-space:pre-wrap}
</style>
<p>First using the usual <code> tag
<code>
%0A function x(arghhh){
%0A return "a very long line of text that will extend the code beyond the boundaries of the margins, guaranteed for the most part, well maybe without you as a warrantee (except in abnormally conditioned perverse environs in which case a warranty is useless)"
%0A }
</code>
and then
<p>with the tag blocked using pre-wrapped lines
<code style=display:block;white-space:pre-wrap>
%0A function x(arghhh){
%0A return "a very long line of text that will extend the code beyond the boundaries of the margins, guaranteed for the most part, well maybe without you as a warrantee (except in abnormally conditioned perverse environs in which case a warranty is useless)"
%0A }
</code>
<br>using an ersatz tag
<codenza>
%0A function x(arghhh){
%0A return "a very long line of text that will extend the code beyond the boundaries of the margins, guaranteed for the most part, well maybe without you as a warrantee (except in abnormally conditioned perverse environs in which case a warranty is useless)"
%0A }
</codenza>
</html>
To bypass google's check, which is what you really want, simply remove the extensions from the file when you send it, and add them back after you download it. For example:
I suggest that you take advantage of the fact that you can assign multiple classes to an element like so:
<ul>
<li class="list">test1</li>
<li class="list">test2</li>
<li class="list last">test3</li>
<li>test4</li>
</ul>
The last element has the list
class like its siblings but also has the last
class which you can use to set any CSS property you want, like so:
ul li.list {
color: #FF0000;
}
ul li.list.last {
background-color: #000;
}
You need to
#include <string>
<iostream>
declares cout
, cin
, not string
.
Better design would be
public static YourObject getMyObject(File configFile){
//process and create an object configure it and return it
}
The easiest way to match both
^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$
and
^[0-9]{3}-[0-9]{3}-[0-9]{4}$
is to use alternation ((...|...)
): specify them as two mostly-separate options:
^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$
By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234
, not (123)123-1234
. So you might want to write:
^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$
(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)
>>> print 5.0 / 2
2.5
>>> print 5.0 // 2
2.0
java.io.File
class contains four static separator variables. For better understanding, Let's understand with the help of some code
Note that all of these are final variables and system dependent.
Here is the java program to print these separator variables. FileSeparator.java
import java.io.File;
public class FileSeparator {
public static void main(String[] args) {
System.out.println("File.separator = "+File.separator);
System.out.println("File.separatorChar = "+File.separatorChar);
System.out.println("File.pathSeparator = "+File.pathSeparator);
System.out.println("File.pathSeparatorChar = "+File.pathSeparatorChar);
}
}
Output of above program on Unix system:
File.separator = /
File.separatorChar = /
File.pathSeparator = :
File.pathSeparatorChar = :
Output of the program on Windows system:
File.separator = \
File.separatorChar = \
File.pathSeparator = ;
File.pathSeparatorChar = ;
To make our program platform independent, we should always use these separators to create file path or read any system variables like PATH, CLASSPATH.
Here is the code snippet showing how to use separators correctly.
//no platform independence, good for Unix systems
File fileUnsafe = new File("tmp/abc.txt");
//platform independent and safe to use across Unix and Windows
File fileSafe = new File("tmp"+File.separator+"abc.txt");
Answered on SO here, question: 403 - Forbidden on basic MVC 3 deploy on iis7.5
Run aspnet_regiis -i
. Often I've found you need to do that to get 4.0 apps to work. Open a command prompt as an Administrator
(right click the command prompt icon and select Run as Administrator):
cd \
cd Windows\Microsoft.NET\Framework\v4.xxx.xxx
aspnet_regiis -i
Once it has installed and registered, make sure you application is using an application pool that is set to .NET 4.0.
UPDATE: I just found an issue with this command. Using -i updated all application pools to ASP.NET 4.0.
Using aspnet_regiis -ir
installs the version of ASP.NET but does not change any web applications to this version. You may also want to review the -iru option.
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Holo.NoActionBar">
<item name="android:windowBackground">@android:color/black</item>
</style>
</resources>
I suggest you look at the article called "Short Introduction to log4j". It contains a short explanation of log levels and demonstrates how they can be used in practice. The basic idea of log levels is that you want to be able to configure how much detail the logs contain depending on the situation. For example, if you are trying to troubleshoot an issue, you would want the logs to be very verbose. In production, you might only want to see warnings and errors.
The log level for each component of your system is usually controlled through a parameter in a configuration file, so it's easy to change. Your code would contain various logging statements with different levels. When responding to an Exception
, you might call Logger.error
. If you want to print the value of a variable at any given point, you might call Logger.debug
. This combination of a configurable logging level and logging statements within your program allow you full control over how your application will log its activity.
In the case of log4j at least, the ordering of log levels is:
DEBUG < INFO < WARN < ERROR < FATAL
Here is a short example from that article demonstrating how log levels work.
// get a logger instance named "com.foo"
Logger logger = Logger.getLogger("com.foo");
// Now set its level. Normally you do not need to set the
// level of a logger programmatically. This is usually done
// in configuration files.
logger.setLevel(Level.INFO);
Logger barlogger = Logger.getLogger("com.foo.Bar");
// This request is enabled, because WARN >= INFO.
logger.warn("Low fuel level.");
// This request is disabled, because DEBUG < INFO.
logger.debug("Starting search for nearest gas station.");
// The logger instance barlogger, named "com.foo.Bar",
// will inherit its level from the logger named
// "com.foo" Thus, the following request is enabled
// because INFO >= INFO.
barlogger.info("Located nearest gas station.");
// This request is disabled, because DEBUG < INFO.
barlogger.debug("Exiting gas station search");
I came here looking for the query string, not how to get values from the query string.
request.query_string
returns the URL parameters as raw byte string (Ref 1).
Example of using request.query_string
:
from flask import Flask, request
app = Flask(__name__)
@app.route('/data', methods=['GET'])
def get_query_string():
return request.query_string
if __name__ == '__main__':
app.run(debug=True)
Output:
References:
var d1 = Date.parse("2012-11-01");
var d2 = Date.parse("2012-11-04");
if (d1 < d2) {
alert ("Error!");
}
IF EXISTS (SELECT 1 FROM Table WHERE FieldValue='')
BEGIN
SELECT TableID FROM Table WHERE FieldValue=''
END
ELSE
BEGIN
INSERT INTO TABLE(FieldValue) VALUES('')
SELECT SCOPE_IDENTITY() AS TableID
END
See here for more information on IF ELSE
Note: written without a SQL Server install handy to double check this but I think it is correct
Also, I've changed the EXISTS bit to do SELECT 1 rather than SELECT * as you don't care what is returned within an EXISTS, as long as something is I've also changed the SCOPE_IDENTITY() bit to return just the identity assuming that TableID is the identity column
For Azure Functions we use this simple extension to Microsoft.Extensions.Logging.ILogger
public static class LoggerExtensions
{
public static void Error(this ILogger logger, string message, Exception exception)
{
if (exception is DbEntityValidationException dbException)
{
message += "\nValidation Errors: ";
foreach (var error in dbException.EntityValidationErrors.SelectMany(entity => entity.ValidationErrors))
{
message += $"\n * Field name: {error.PropertyName}, Error message: {error.ErrorMessage}";
}
}
logger.LogError(default(EventId), exception, message);
}
}
and example usage:
try
{
do something with request and EF
}
catch (Exception e)
{
log.Error($"Failed to create customer due to an exception: {e.Message}", e);
return await StringResponseUtil.CreateResponse(HttpStatusCode.InternalServerError, e.Message);
}
Its just a 2 line of code.
import org.springframework.web.client.RestTemplate;
RestTemplate restTemplate = new RestTemplate();
YourBean obj = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", YourBean.class);
I tried this, I've got something like
script type="text/javascript" src="createDiv.php?id=" script
AND In createDiv.php I Have
document getElementbyid(imgslide).appendchild(imgslide5).innerHTML = 'php echo $helloworld; ';
And I got supermad because the php at the beginning of the createDiv.php I made the $helloWorld
php variable was formatted cut and paste from the html page
But it wouldn't work cause Of whitespaces was anyone gonna tell anyone about the whitespace problem cause my real php whitespace still works but not this one.
Answer is as follows:
super.Mymethod();
super(); // calls base class Superclass constructor.
super(parameter list); // calls base class parameterized constructor.
super.method(); // calls base class method.
When generating mapping files using doctrine I ran into same issue. I fixed it by removing all comments that some fields had in the database.
There's a headers parameter in the config object you pass to $http
for per-call headers:
$http({method: 'GET', url: 'www.google.com/someapi', headers: {
'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});
Or with the shortcut method:
$http.get('www.google.com/someapi', {
headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});
The list of the valid parameters is available in the $http service documentation.
The PHPMailer help docs on this specific error helped to get me on the right path.
What we found is that php.ini did not have the sendmail_path defined, so I added that with sendmail_path = /usr/sbin/sendmail -t -i;
Some of the tutorials I found that are easy to understand are:
It makes way more sense to break up your list into page-sized chunks, and only query your database one chunk at a time. This drastically reduces server processing time and page load time, as well as gives your user smaller pieces of info to digest, so he doesn't choke on whatever crap you're trying to feed him. The act of doing this is called pagination.
A basic pagination routine seems long and scary at first, but once you close your eyes, take a deep breath, and look at each piece of the script individually, you will find it's actually pretty easy stuff
The script:
// find out how many rows are in the table
$sql = "SELECT COUNT(*) FROM numbers";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];
// number of rows to show per page
$rowsperpage = 10;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = (int) $_GET['currentpage'];
} else {
// default page num
$currentpage = 1;
} // end if
// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
$sql = "SELECT id, number FROM numbers LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) {
// echo data
echo $list['id'] . " : " . $list['number'] . "<br />";
} // end while
/****** build the pagination links ******/
// range of num links to show
$range = 3;
// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if
// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
// 'highlight' it but don't make a link
echo " [<b>$x</b>] ";
// if not current page...
} else {
// make it a link
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
// echo forward link for lastpage
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
?>
This tutorial is intended for developers who wish to give their users the ability to step through a large number of database rows in manageable chunks instead of the whole lot in one go.
This is, unfortunately a quite common problem on Windows where the icons are either not updated or rather disappearing. I find it quite annoying. It usually is fixed by either refreshing the Windows folder (F5) or, by doing a SVN Clean up,
Right click on the folder -> TortoiseSVN -> Clean up...
Select Clean up working copy status
I have never been able to solve this permanently, this is only a work-around. Keeping TortoiseSVN on the latest version may or may not help.
Note that the clean up will only clean up your local working copy, it wont do anything to the actual repository. Its a safe operation.
Apparently this is not enough according to your comment. Do you have lots of other programs that are also using overlay icons? If so maybe you can find a solution in this thread: TortoiseSVN icons not showing up under Windows 7? The second most voted answer also deals with network drives etc. Its a good read.
Also, have you rebooted your computer after the install? From the TortoiseSVN FAQ:
You rebooted your PC of course after the installation? If you haven't please do so now. TortoiseSVN is a windows Explorer Shell extension and will be loaded together with Explorer.
...
Otherwise, try doing a repair install (and reboot of course).
a solution can be having the close inside your modal
take a look at this simple example
I think the variable should be in the same block:
@{bool isUserConnected = string.IsNullOrEmpty(Model.CreatorFullName);
if (isUserConnected)
{ // meaning that the viewing user has not been saved
<div>
<div> click to join us </div>
<a id="login" href="javascript:void(0);" style="display: inline; ">join</a>
</div>
}
}
This may be old, but... if you change the link in google stock list as below:
It means, starting for row 1 to 30000. It shows all results in one page.
You may automate it using any language or just export the table to excel.
Hope it helps.
They work at different levels.
The simplest way to view the difference, from a beginner perspective is that jQuery is essentially an abstract of JavaScript, so the way we design a page for JavaScript is pretty much how we will do it for jQuery. Start with the DOM then build a behavior layer on top of that. Not so with Angular.Js. The process really begins from the ground up, so the end result is the desired view.
With jQuery you do dom-manipulations, with Angular.Js you create whole web-applications.
jQuery was built to abstract away the various browser idiosyncracies, and work with the DOM without having to add IE6 checks and so on. Over time, it developed a nice, robust API which allowed us to do a lot of things, but at its core, it is meant for dealing with the DOM, finding elements, changing UI, and so on. Think of it as working directly with nuts and bolts.
Angular.Js was built as a layer on top of jQuery, to add MVC concepts to front end engineering. Instead of giving you APIs to work with DOM, Angular.Js gives you data-binding, templating, custom components (similar to jQuery UI, but declarative instead of triggering through JS) and a whole lot more. Think of it as working at a higher level, with components that you can hook together, instead of directly at the nuts and bolts level.
Additionally, Angular.Js gives you structures and concepts that apply to various projects, like Controllers, Services, and Directives. jQuery itself can be used in multiple (gazillion) ways to do the same thing. Thankfully, that is way less with Angular.Js, which makes it easier to get into and out of projects. It offers a sane way for multiple people to contribute to the same project, without having to relearn a system from scratch.
A short comparison can be this-
And much more
Think this helps.
More can be found-
Somewhat similar to your original attempt, but more Pythonic, is to use Python's standard negative-indexing convention to count backwards from the end:
df[df.columns[-1]]
The Array.prototype.shift
method removes the first element from an array, and returns it. It modifies the original array.
var a = [1,2,3]
// [1,2,3]
a.shift()
// 1
a
//[2,3]
You can use
if errorlevel 1 echo Unsuccessful
in some cases. This depends on the last command returning a proper exit code. You won't be able to tell that there is anything wrong if your program returns normally even if there was an abnormal condition.
Caution with programs like Robocopy, which require a more nuanced approach, as the error level returned from that is a bitmask which contains more than just a boolean information and the actual success code is, AFAIK, 3.
another language meta tag is og:locale and you can define og:locale meta tag for social media
<meta property="og:locale" content="en" />
With [email protected] or later you can install types with npm install
npm install --save-dev @types/jasmine
then import the types automatically using the typeRoots option in tsconfig.json.
"typeRoots": [
"node_modules/@types"
],
This solution does not require import {} from 'jasmine'; in each spec file.
Here is another implementation that will operate safely to tokenize a string-literal matching the prototype requested in the question returning an allocated pointer-to-pointer to char (e.g. char **
). The delimiter string can contain multiple characters, and the input string can contain any number of tokens. All allocations and reallocations are handled by malloc
or realloc
without POSIX strdup
.
The initial number of pointers allocated is controlled by the NPTRS
constant and the only limitation is that it be greater than zero. The char **
returned contains a sentinel NULL
after the last token similar to *argv[]
and in the form usable by execv
, execvp
and execve
.
As with strtok()
multiple sequential delimiters are treated as a single delimiter, so "JAN,FEB,MAR,APR,MAY,,,JUN,JUL,AUG,SEP,OCT,NOV,DEC"
will be parsed as if only a single ','
separates "MAY,JUN"
.
The function below is commented in-line and a short main()
was added splitting the months. The initial number of pointers allocated was set at 2
to force three reallocation during tokenizing the input string:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NPTRS 2 /* initial number of pointers to allocate (must be > 0) */
/* split src into tokens with sentinel NULL after last token.
* return allocated pointer-to-pointer with sentinel NULL on success,
* or NULL on failure to allocate initial block of pointers. The number
* of allocated pointers are doubled each time reallocation required.
*/
char **strsplit (const char *src, const char *delim)
{
int i = 0, in = 0, nptrs = NPTRS; /* index, in/out flag, ptr count */
char **dest = NULL; /* ptr-to-ptr to allocate/fill */
const char *p = src, *ep = p; /* pointer and end-pointer */
/* allocate/validate nptrs pointers for dest */
if (!(dest = malloc (nptrs * sizeof *dest))) {
perror ("malloc-dest");
return NULL;
}
*dest = NULL; /* set first pointer as sentinel NULL */
for (;;) { /* loop continually until end of src reached */
if (!*ep || strchr (delim, *ep)) { /* if at nul-char or delimiter char */
size_t len = ep - p; /* get length of token */
if (in && len) { /* in-word and chars in token */
if (i == nptrs - 1) { /* used pointer == allocated - 1? */
/* realloc dest to temporary pointer/validate */
void *tmp = realloc (dest, 2 * nptrs * sizeof *dest);
if (!tmp) {
perror ("realloc-dest");
break; /* don't exit, original dest still valid */
}
dest = tmp; /* assign reallocated block to dest */
nptrs *= 2; /* increment allocated pointer count */
}
/* allocate/validate storage for token */
if (!(dest[i] = malloc (len + 1))) {
perror ("malloc-dest[i]");
break;
}
memcpy (dest[i], p, len); /* copy len chars to storage */
dest[i++][len] = 0; /* nul-terminate, advance index */
dest[i] = NULL; /* set next pointer NULL */
}
if (!*ep) /* if at end, break */
break;
in = 0; /* set in-word flag 0 (false) */
}
else { /* normal word char */
if (!in) /* if not in-word */
p = ep; /* update start to end-pointer */
in = 1; /* set in-word flag 1 (true) */
}
ep++; /* advance to next character */
}
return dest;
}
int main (void) {
char *str = "JAN,FEB,MAR,APR,MAY,,,JUN,JUL,AUG,SEP,OCT,NOV,DEC",
**tokens; /* pointer to pointer to char */
if ((tokens = strsplit (str, ","))) { /* split string into tokens */
for (char **p = tokens; *p; p++) { /* loop over filled pointers */
puts (*p);
free (*p); /* don't forget to free allocated strings */
}
free (tokens); /* and pointers */
}
}
Example Use/Output
$ ./bin/splitinput
JAN
FEB
MAR
APR
MAY
JUN
JUL
AUG
SEP
OCT
NOV
DEC
Let me know if you have any further questions.
You can't convert binary data to String. As a solution you can encode binary data and then convert to String. For example, look at this How do you convert binary data to Strings and back in Java?
Set the PATH as below:
In the csh shell - type setenv PATH "$PATH:/usr/local/bin/python"
and press Enter.
In the bash shell (Linux) - type export PATH="$PATH:/usr/local/bin/python"
and press Enter.
In the sh or ksh shell - type PATH="$PATH:/usr/local/bin/python"
and press Enter.
Note - /usr/local/bin/python
is the path of the Python directory
now run as below:
-bash-4.2$ python test.py
Hello, Python!
You don't actually need to run a command from an xterm session, you can run it directly:
String[] arguments = new String[] {"/path/to/executable", "arg0", "arg1", "etc"};
Process proc = new ProcessBuilder(arguments).start();
If the process responds interactively to the input stream, and you want to inject values, then do what you did before:
OutputStream out = proc.getOutputStream();
out.write("command\n");
out.flush();
Don't forget the '\n' at the end though as most apps will use it to identify the end of a single command's input.
If you use mod_rewrite to hide the extension of your scripts, or if you just like pretty URLs that end in /, then you might want to approach this from the other direction. Tell nginx to let anything with a non-static extension to go through to apache. For example:
location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm)$
{
root /path/to/static-content;
}
location ~* ^!.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm)$ {
if (!-f $request_filename) {
return 404;
}
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
}
I found the first part of this snippet over at: http://code.google.com/p/scalr/wiki/NginxStatic
Here is way to avoid absolute divs and tables if you know parent's height:
<div class="parent">
<div class="child"> <a href="#">Home</a>
</div>
</div>
CSS:
.parent {
line-height:80px;
border: 1px solid black;
}
.child {
line-height:normal;
display: inline-block;
vertical-align:bottom;
border: 1px solid red;
}
JsFiddle:
This should cover most basic use cases.
const capitalize = (str) => {
if (typeof str !== 'string') {
throw Error('Feed me string')
} else if (!str) {
return ''
} else {
return str
.split(' ')
.map(s => {
if (s.length == 1 ) {
return s.toUpperCase()
} else {
const firstLetter = s.split('')[0].toUpperCase()
const restOfStr = s.substr(1, s.length).toLowerCase()
return firstLetter + restOfStr
}
})
.join(' ')
}
}
capitalize('THIS IS A BOOK') // => This Is A Book
capitalize('this is a book') // => This Is A Book
capitalize('a 2nd 5 hour boOk thIs weEk') // => A 2nd 5 Hour Book This Week
Edit: Improved readability of mapping.
save.patch
file to wherever (including binary files).git apply <file>
Note: it diff's the currently staged files too.
$ git diff --binary --staged HEAD > save.patch
$ git reset --hard
$ <transport it>
$ git apply save.patch
for those who are using IIS with php, on IIS it server side update web.config file it root directory (wwwroot) and add this
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<directoryBrowse enabled="true" />
<httpProtocol>
<customHeaders>
<add name="Control-Allow-Origin" value="*"/>
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
after that restart IIS server, type IISReset in RUN and enter
Simplified example (with counter):
With Me.lstbox
.ColumnCount = 2
.ColumnWidths = "60;60"
.AddItem
.List(i, 0) = Company_ID
.List(i, 1) = Company_name
i = i + 1
end with
Make sure to start the counter with 0, not 1 to fill up a listbox.
You can also use a "here document" to do the same thing:
VARIABLE=SOMEVALUE
sqlplus connectioninfo << HERE
start file1.sql
start file2.sql $VARIABLE
quit
HERE
if( undefined == $('#isAgeSelected').attr('checked') ) {
$("#txtAge").hide();
} else {
$("#txtAge").show();
}
The simplest solution I found was combination of mysql
and jq
commands with JSON_OBJECT
query. Actually jq
is not required if JSON Lines format is good enough.
Dump from remote server to local file example.
ssh remote_server \
"mysql \
--silent \
--raw \
--host "" --port 3306 \
--user "" --password="" \
table \
-e \"SELECT JSON_OBJECT('key', value) FROM table\" |
jq --slurp --ascii-output ." \
> dump.json
books
table example
+----+-------+
| id | book |
+----+-------+
| 1 | book1 |
| 2 | book2 |
| 3 | book3 |
+----+-------+
Query would looks like:
SELECT JSON_OBJECT('id', id, 'book', book) FROM books;
dump.json
output
[
{
"id": "1",
"book": "book1"
},
{
"id": "2",
"book": "book2"
},
{
"id": "3",
"book": "book3"
}
]
Another form that works with Postgres 9.1+ is combining a Common Table Expression with the USING statement for the join.
WITH prod AS (select m_product_id, upc from m_product where upc='7094')
DELETE FROM m_productprice B
USING prod C
WHERE B.m_product_id = C.m_product_id
AND B.m_pricelist_version_id = '1000020';
var d = new Date();
d.setMonth(d.getMonth() - 3);
This works for January. Run this snippet:
var d = new Date("January 14, 2012");_x000D_
console.log(d.toLocaleDateString());_x000D_
d.setMonth(d.getMonth() - 3);_x000D_
console.log(d.toLocaleDateString());
_x000D_
There are some caveats...
A month is a curious thing. How do you define 1 month? 30 days? Most people will say that one month ago means the same day of the month on the previous month citation needed. But more than half the time, that is 31 days ago, not 30. And if today is the 31st of the month (and it isn't August or Decemeber), that day of the month doesn't exist in the previous month.
Interestingly, Google agrees with JavaScript if you ask it what day is one month before another day:
It also says that one month is 30.4167 days long:
So, is one month before March 31st the same day as one month before March 28th, 3 days earlier? This all depends on what you mean by "one month before". Go have a conversation with your product owner.
If you want to do like momentjs does, and correct these last day of the month errors by moving to the last day of the month, you can do something like this:
const d = new Date("March 31, 2019");_x000D_
console.log(d.toLocaleDateString());_x000D_
const month = d.getMonth();_x000D_
d.setMonth(d.getMonth() - 1);_x000D_
while (d.getMonth() === month) {_x000D_
d.setDate(d.getDate() - 1);_x000D_
}_x000D_
console.log(d.toLocaleDateString());
_x000D_
If your requirements are more complicated than that, use some math and write some code. You are a developer! You don't have to install a library! You don't have to copy and paste from stackoverflow! You can develop the code yourself to do precisely what you need!
You're right that .import
is the way to go, but that's a command from the SQLite3.exe shell. A lot of the top answers to this question involve native python loops, but if your files are large (mine are 10^6 to 10^7 records), you want to avoid reading everything into pandas or using a native python list comprehension/loop (though I did not time them for comparison).
For large files, I believe the best option is to create the empty table in advance using sqlite3.execute("CREATE TABLE...")
, strip the headers from your CSV files, and then use subprocess.run()
to execute sqlite's import statement. Since the last part is I believe the most pertinent, I will start with that.
subprocess.run()
from pathlib import Path
db_name = Path('my.db').resolve()
csv_file = Path('file.csv').resolve()
result = subprocess.run(['sqlite3',
str(db_name),
'-cmd',
'.mode csv',
'.import '+str(csv_file).replace('\\','\\\\')
+' <table_name>'],
capture_output=True)
Explanation
From the command line, the command you're looking for is sqlite3 my.db -cmd ".mode csv" ".import file.csv table"
. subprocess.run()
runs a command line process. The argument to subprocess.run()
is a sequence of strings which are interpreted as a command followed by all of it's arguments.
sqlite3 my.db
opens the database -cmd
flag after the database allows you to pass multiple follow on commands to the sqlite program. In the shell, each command has to be in quotes, but here, they just need to be their own element of the sequence'.mode csv'
does what you'd expect'.import '+str(csv_file).replace('\\','\\\\')+' <table_name>'
is the import command.-cmd
as quoted strings, you need to double up your backslashes if you have a windows directory path.Not really the main point of the question, but here's what I used. Again, I didn't want to read the whole files into memory at any point:
with open(csv, "r") as source:
source.readline()
with open(str(csv)+"_nohead", "w") as target:
shutil.copyfileobj(source, target)
ifeq ($(GCC_MINOR), 4) CFLAGS += -fno-strict-overflow endif ifeq ($(GCC_MINOR), 5) CFLAGS += -fno-strict-overflow endif
Another you can consider using in this case is:
GCC42_OR_LATER = $(shell $(CXX) -v 2>&1 | $(EGREP) -c "^gcc version (4.[2-9]|[5-9])")
# -Wstrict-overflow: http://www.airs.com/blog/archives/120
ifeq ($(GCC42_OR_LATER),1)
CFLAGS += -Wstrict-overflow
endif
I actually use the same in my code because I don't want to maintain a separate config
or Configure
.
But you have to use a portable, non-anemic make
, like GNU make (gmake
), and not Posix's make
.
And it does not address the issue of logical AND
and OR
.
Add & Remove Classes (tested on IE8+)
Add trim() to IE (taken from: .trim() in JavaScript not working in IE)
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
Add and Remove Classes:
function addClass(element,className) {
var currentClassName = element.getAttribute("class");
if (typeof currentClassName!== "undefined" && currentClassName) {
element.setAttribute("class",currentClassName + " "+ className);
}
else {
element.setAttribute("class",className);
}
}
function removeClass(element,className) {
var currentClassName = element.getAttribute("class");
if (typeof currentClassName!== "undefined" && currentClassName) {
var class2RemoveIndex = currentClassName.indexOf(className);
if (class2RemoveIndex != -1) {
var class2Remove = currentClassName.substr(class2RemoveIndex, className.length);
var updatedClassName = currentClassName.replace(class2Remove,"").trim();
element.setAttribute("class",updatedClassName);
}
}
else {
element.removeAttribute("class");
}
}
Usage:
var targetElement = document.getElementById("myElement");
addClass(targetElement,"someClass");
removeClass(targetElement,"someClass");
A working JSFIDDLE: http://jsfiddle.net/fixit/bac2vuzh/1/
Swift 5
extension String {
func convertToDictionary() -> [String: Any]? {
if let data = data(using: .utf8) {
return try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
}
return nil
}
}
Assuming that winrar.exe
is in the PATH
, then Runtime.exec
is capable of finding it, if it is not, you will need to supply the fully qualified path to it, for example, assuming winrar.exe
is installed in C:/Program Files/WinRAR
you would need to use something like...
p=r.exec("C:/Program Files/WinRAR/winrar x h:\\myjar.jar *.* h:\\new");
Personally, I would recommend that you use ProcessBuilder
as it has some additional configuration abilities amongst other things. Where possible, you should also separate your command and parameters into separate String
elements, it deals with things like spaces much better then a single String
variable, for example...
ProcessBuilder pb = new ProcessBuilder(
"C:/Program Files/WinRAR/winrar",
"x",
"myjar.jar",
"*.*",
"new");
pb.directory(new File("H:/"));
pb. redirectErrorStream(true);
Process p = pb.start();
Don't forget to read the contents of the InputStream
from the process, as failing to do so may stall the process
Similar to unutbu above, you could also use applymap
as follows:
import pandas as pd
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
index=['foo','bar','baz','quux'],
columns=['cost'])
df = df.applymap("${0:.2f}".format)
In Linux:
1) find where is sqlplus located,
[oracle@LINUX db_1]$ `which sqlplus`
/app/oracle/product/11.2.0/db_1/bin/sqlplus
2) Determine the file type,
[oracle@LINUX db_1]$ file /app/oracle/product/11.2.0/db_1/bin/sqlplus
/app/oracle/product/11.2.0/db_1/bin/sqlplus: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs). For GNU/Linux 2.6.18, not stripped.
High performance - every Double
object wraps a single double
value. If you want to store all these values into a double[]
array, then you have to iterate over the collection of Double
instances. A O(1)
mapping is not possible, this should be the fastest you can get:
double[] target = new double[doubles.size()];
for (int i = 0; i < target.length; i++) {
target[i] = doubles.get(i).doubleValue(); // java 1.4 style
// or:
target[i] = doubles.get(i); // java 1.5+ style (outboxing)
}
Thanks for the additional question in the comments ;) Here's the sourcecode of the fitting ArrayUtils#toPrimitive
method:
public static double[] toPrimitive(Double[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_DOUBLE_ARRAY;
}
final double[] result = new double[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = array[i].doubleValue();
}
return result;
}
(And trust me, I didn't use it for my first answer - even though it looks ... pretty similiar :-D )
By the way, the complexity of Marcelos answer is O(2n), because it iterates twice (behind the scenes): first to make a Double[]
from the list, then to unwrap the double
values.
My experience with this is that getTextBounds
will return that absolute minimal bounding rect that encapsulates the text, not necessarily the measured width used when rendering. I also want to say that measureText
assumes one line.
In order to get accurate measuring results, you should use the StaticLayout
to render the text and pull out the measurements.
For example:
String text = "text";
TextPaint textPaint = textView.getPaint();
int boundedWidth = 1000;
StaticLayout layout = new StaticLayout(text, textPaint, boundedWidth , Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
int height = layout.getHeight();
This post is right from SAP on Sep 20, 2012.
In short, they are still working on a release of Crystal Reports that will support VS2012 (including support for Windows 8) It will come in the form of a service pack release that updates the version currently supporting VS2010. At that time they will drop 2010/2012 from the name and simply call it Crystal Reports Developer.
If you want to download that version you can find it here.
Further, service packs etc. when released can be found here.
I would also add that I am currently using Visual Studio 2012. As long as you don't edit existing reports they continue to compile and work fine. Even on Windows 8. When I need to modify a report I can still open the project with VS2010, do my work, save my changes, and then switch back to 2012. It's a little bit of a pain but the ability for VS2010 and VS2012 to co-exist is nice in this regard. I'm also using TFS2012 and so far it hasn't had a problem with me modifying files in 2010 on a "2012" solution.
A solution that responds to the input
event instead of key events (like keyup
) will give a smooth experience (no wiggles), and also works when changes are made without the keyboard (context menu, mouse drag, other device...).
The code below will look for input elements that have both a placeholder
attribute and a data-slots
attribute. The latter should define the character(s) in the placeholder that is/are intended as input slot, for example, "_". An optional data-accept
attribute can be provided with a regular expression that defines which characters are allowed in such a slot. The default is \d
, i.e. digits.
// This code empowers all input tags having a placeholder and data-slots attribute_x000D_
document.addEventListener('DOMContentLoaded', () => {_x000D_
for (const el of document.querySelectorAll("[placeholder][data-slots]")) {_x000D_
const pattern = el.getAttribute("placeholder"),_x000D_
slots = new Set(el.dataset.slots || "_"),_x000D_
prev = (j => Array.from(pattern, (c,i) => slots.has(c)? j=i+1: j))(0),_x000D_
first = [...pattern].findIndex(c => slots.has(c)),_x000D_
accept = new RegExp(el.dataset.accept || "\\d", "g"),_x000D_
clean = input => {_x000D_
input = input.match(accept) || [];_x000D_
return Array.from(pattern, c =>_x000D_
input[0] === c || slots.has(c) ? input.shift() || c : c_x000D_
);_x000D_
},_x000D_
format = () => {_x000D_
const [i, j] = [el.selectionStart, el.selectionEnd].map(i => {_x000D_
i = clean(el.value.slice(0, i)).findIndex(c => slots.has(c));_x000D_
return i<0? prev[prev.length-1]: back? prev[i-1] || first: i;_x000D_
});_x000D_
el.value = clean(el.value).join``;_x000D_
el.setSelectionRange(i, j);_x000D_
back = false;_x000D_
};_x000D_
let back = false;_x000D_
el.addEventListener("keydown", (e) => back = e.key === "Backspace");_x000D_
el.addEventListener("input", format);_x000D_
el.addEventListener("focus", format);_x000D_
el.addEventListener("blur", () => el.value === pattern && (el.value=""));_x000D_
}_x000D_
});
_x000D_
[data-slots] { font-family: monospace }
_x000D_
<label>Date time: _x000D_
<input placeholder="dd/mm/yyyy hh:mm" data-slots="dmyh">_x000D_
</label><br>_x000D_
<label>Telephone:_x000D_
<input placeholder="+1 (___) ___-____" data-slots="_">_x000D_
</label><br>_x000D_
<label>MAC Address:_x000D_
<input placeholder="XX:XX:XX:XX:XX:XX" data-slots="X" data-accept="[\dA-H]">_x000D_
</label><br>_x000D_
<label>Signed number (3 digits):_x000D_
<input placeholder="±___" data-slots="±_" data-accept="^[+-]|(?!^)\d" size="4">_x000D_
</label><br>_x000D_
<label>Alphanumeric:_x000D_
<input placeholder="__-__-__-____" data-slots="_" data-accept="\w" size="13">_x000D_
</label><br>
_x000D_
Without using third-party integration tools, I could enhance the condition a bit and use DropBox and other similar cloud disk services such as SpiderOak with Git.
The goal is to avoid the synchronization in the middle of these files modifications, as it can upload a partial state and will then download it back, completely corrupting your git state.
To avoid this issue, I did:
git bundle create my_repo.git --all
.It's not perfect as there is no guarantee it won't mess up the git state again, but it helps and for the moment I did not get any issue.
(\d+)\s+(\(.*?\))?\s?Z
Note the escaped parentheses, and the ?
(zero or once) quantifiers. Any of the groups you don't want to capture can be (?:
non-capture groups).
I agree about the spaces. \s
is a better option there. I also changed the quantifier to insure there are digits at the beginning. As far as newlines, that would depend on context: if the file is parsed line by line it won't be a problem. Another option is to anchor the start and end of the line (add a ^
at the front and a $
at the end).
And the Purescript answer, for people using Halogen:
import CSS (display, displayNone)
import Halogen.HTML as HH
import Halogen.HTML.CSS as CSS
render state =
HH.div [ CSS.style $ display displayNone ] [ HH.text "Hi there!" ]
If you "inspect element", you'll see something like:
<div style="display: none">Hi there!</div>
but nothing will actually display on your screen, as expected.
You need to declare the type of the protocol as AnyObject
.
protocol ProtocolNameDelegate: AnyObject {
// Protocol stuff goes here
}
class SomeClass {
weak var delegate: ProtocolNameDelegate?
}
Using AnyObject
you say that only classes can conform to this protocol, whereas structs or enums can't.
I've ran into the same issue and these two links solved for me:
The first one is this one: How do I retrieve the logged in Google account on android phones?
Which presents the code for retrieving the accounts associated with the phone. Basically you will need something like this:
AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
Account[] list = manager.getAccounts();
And to add the permissions in the AndroidManifest.xml
<uses-permission android:name="android.permission.GET_ACCOUNTS"></uses-permission>
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS"></uses-permission>
Additionally, if you are using the Emulator the following link will help you to set it up with an account : Android Emulator - Trouble creating user accounts
Basically, it says that you must create an android device based on a API Level and not the SDK Version (like is usually done).
the simple way I found out: add a "li" tag on the right side of an "a" tag List item
<li></span><a><span id="expand1"></span></a></li>
On CSS file create this below:
#expand1 {
padding-left: 40px;
}
Integer[] arr = { 0, 1, 1, 2, 3, 5, 8, 13, 21 };
List<Integer> arrlst = Arrays.asList(arr);
System.out.println(arrlst.lastIndexOf(1));
If u want a direct/ quick away, without assing to variables:
{
urArray.map((prop, key) => {
console.log(emp);
return <Picker.Item label={emp.Name} value={emp.id} />;
})
}
The short answer is install Media Feature Pack for N and KN versions of Windows 8.1
Big thanks to Matej Drolc that had it solved in hit blog post here.
This error is caused by:
Y = Dataset.iloc[:,18].values
Indexing is out of bounds here most probably because there are less than 19 columns in your Dataset, so column 18 does not exist. The following code you provided doesn't use Y at all, so you can just comment out this line for now.
You could get a JavaScript object containing the parameters with something like this:
var regex = /[?&]([^=#]+)=([^&#]*)/g,
url = window.location.href,
params = {},
match;
while(match = regex.exec(url)) {
params[match[1]] = match[2];
}
The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by =
characters, and pairs themselves separated by &
characters (or an =
character for the first one). For your example, the above would result in:
{v: "123", p: "hello"}
Here's a working example.
Not an answer to OP's question but it's worth mentioning that there is the viridis
package which has good color palettes for sequential data. They are perceptually uniform, colorblind safe and printer-friendly.
To get the palette, simply install the package and use the function viridis_pal()
. There are four options "A", "B", "C" and "D" to choose
install.packages("viridis")
library(viridis)
viridis_pal(option = "D")(n) # n = number of colors seeked
There is also an excellent talk explaining the complexity of good colormaps on YouTube:
A Better Default Colormap for Matplotlib | SciPy 2015 | Nathaniel Smith and Stéfan van der Walt
static arrary meens with giving on elements in side the array
dynamic arrary meens without giving on elements in side the array
example:
char a[10]; //static array
char a[]; //dynamic array
git format-patch
also has the -B
flag.
The description in the man page leaves much to be desired, but in simple language it's the threshold format-patch will abide to before doing a total re-write of the file (by a single deletion of everything old, followed by a single insertion of everything new).
This proved very useful for me when manual editing was too cumbersome, and the source was more authoritative than my destination.
An example:
git format-patch -B10% --stdout my_tag_name > big_patch.patch
git am -3 -i < big_patch.patch
one
has not been assigned so points to an unpredictable location. You should either place it on the stack:
Vector one;
one.a = 12;
one.b = 13;
one.c = -11
or dynamically allocate memory for it:
Vector* one = malloc(sizeof(*one))
one->a = 12;
one->b = 13;
one->c = -11
free(one);
Note the use of free
in this case. In general, you'll need exactly one call to free
for each call made to malloc
.
There is this plugin on github that load content into an element. Here is the repo
Just as an addition: This way you can access properties with names that would be otherwise unusable
$x = new StdClass;$prop = 'a b'; $x->$prop = 1; $x->{'x y'} = 2; var_dump($x);
object(stdClass)#1 (2) { ["a b"]=> int(1) ["x y"]=> int(2) }(not that you should, but in case you have to).
-- create test table "Accounts"
create table Accounts (
c_ID int primary key
,first_name varchar(100)
,last_name varchar(100)
,city varchar(100)
);
insert into Accounts values (101, 'Sebastian', 'Volk', 'Frankfurt' );
insert into Accounts values (102, 'Beate', 'Mueller', 'Hamburg' );
insert into Accounts values (103, 'John', 'Walker', 'Washington' );
insert into Accounts values (104, 'Britney', 'Sears', 'Holywood' );
insert into Accounts values (105, 'Sarah', 'Schmidt', 'Mainz' );
insert into Accounts values (106, 'George', 'Lewis', 'New Jersey' );
insert into Accounts values (107, 'Jian-xin', 'Wang', 'Peking' );
insert into Accounts values (108, 'Katrina', 'Khan', 'Bolywood' );
-- declare table variable
declare @tb_FirstName table(name varchar(100));
insert into @tb_FirstName values ('John'), ('Sarah'), ('George');
SELECT *
FROM Accounts
WHERE first_name in (select name from @tb_FirstName);
SELECT *
FROM Accounts
WHERE first_name not in (select name from @tb_FirstName);
go
drop table Accounts;
go
This is the easiest one , Just define a Function and then a Tkinter Label & Button . Pressing the Button changes the text in the label. The difference that you would when defining the Label is that use the text variable instead of text. Code is tested and working.
from tkinter import *
master = Tk()
def change_text():
my_var.set("Second click")
my_var = StringVar()
my_var.set("First click")
label = Label(mas,textvariable=my_var,fg="red")
button = Button(mas,text="Submit",command = change_text)
button.pack()
label.pack()
master.mainloop()
I found the other examples unclear, so I did my own test which confirmed that a class instance is passed by reference and as such actions done to the class will affect the source instance.
In other words, my Increment method modifies its parameter myClass everytime its called.
class Program
{
static void Main(string[] args)
{
MyClass myClass = new MyClass();
Console.WriteLine(myClass.Value); // Displays 1
Increment(myClass);
Console.WriteLine(myClass.Value); // Displays 2
Increment(myClass);
Console.WriteLine(myClass.Value); // Displays 3
Increment(myClass);
Console.WriteLine(myClass.Value); // Displays 4
Console.WriteLine("Hit Enter to exit.");
Console.ReadLine();
}
public static void Increment(MyClass myClassRef)
{
myClassRef.Value++;
}
}
public class MyClass
{
public int Value {get;set;}
public MyClass()
{
Value = 1;
}
}
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class Default3 : System.Web.UI.Page
{
DataTable dt = new DataTable();
DataSet Gds = new DataSet();
// DataColumn colm1 = new DataColumn();
//DataColumn colm2 = new DataColumn();
protected void Page_Load(object sender, EventArgs e)
{
dt.Columns.Add("ExpId", typeof(int));
dt.Columns.Add("FirstName", typeof(string));
}
protected void BtnLoad_Click(object sender, EventArgs e)
{
// gvLoad is Grid View Id
if (gvLoad.Rows.Count == 0)
{
Gds.Tables.Add(tblLoad());
}
else
{
dt = tblGridRow();
dt.Rows.Add(tblRow());
Gds.Tables.Add(dt);
}
gvLoad.DataSource = Gds;
gvLoad.DataBind();
}
protected DataTable tblLoad()
{
dt.Rows.Add(tblRow());
return dt;
}
protected DataRow tblRow()
{
DataRow dr;
dr = dt.NewRow();
dr["Exp Id"] = Convert.ToInt16(txtId.Text);
dr["First Name"] = Convert.ToString(txtName.Text);
return dr;
}
protected DataTable tblGridRow()
{
DataRow dr;
for (int i = 0; i < gvLoad.Rows.Count; i++)
{
if (gvLoad.Rows[i].Cells[0].Text != null)
{
dr = dt.NewRow();
dr["Exp Id"] = gvLoad.Rows[i].Cells[1].Text.ToString();
dr["First Name"] = gvLoad.Rows[i].Cells[2].Text.ToString();
dt.Rows.Add(dr);
}
}
return dt;
}
protected void btn_Click(object sender, EventArgs e)
{
dt = tblGridRow();
dt.Rows.Add(tblRow());
Session["tab"] = dt;
// Response.Redirect("Default.aspx");
}
protected void gvLoad_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
dt = tblGridRow();
dt.Rows.RemoveAt(e.RowIndex);
gvLoad.DataSource = dt;
gvLoad.DataBind();
}
}
It's best to use miske's answer.
If you really want to use natecarlson's repository, the instructions just below can do any of the following:
apt-get update
gives a 404
error after add-apt-repository
apt-get update
gives a NO_PUBKEY
error after manually adding it to /etc/apt/sources.list
Open a terminal and run the following:
sudo -i
Enter your password if necessary, then paste the following into the terminal:
export GOOD_RELEASE='precise'
export BAD_RELEASE="`lsb_release -cs`"
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-add-repository -y ppa:natecarlson/maven3
mv natecarlson-maven3-${BAD_RELEASE}.list natecarlson-maven3-${GOOD_RELEASE}.list
sed -i "s/${BAD_RELEASE}/${GOOD_RELEASE}/" natecarlson-maven3-${GOOD_RELEASE}.list
apt-get update
exit
echo Done!
If you installed natecarlson's repository (either using add-apt-repository
or manually added to /etc/apt/sources.list
) and you don't want it anymore, open a terminal and run the following:
sudo -i
Enter your password if necessary, then paste the following into the terminal:
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-get update
exit
echo Done!
I don't know if setLogLevel() will return in the final 2.0 version of Retrofit but for now you can use an interceptor for logging.
A good example can found in OkHttp wiki: https://github.com/square/okhttp/wiki/Interceptors
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new LoggingInterceptor());
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://www.yourjsonapi.com")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
To toggle the input's disabled attribute was surprisingly complex. The issue for me was twofold:
(1) Remember: the input's "disabled" attribute is NOT a Boolean attribute.
The mere presence of the attribute means that the input is disabled.
However, the Vue.js creators have prepared this... https://vuejs.org/v2/guide/syntax.html#Attributes
(Thanks to @connexo for this... How to add disabled attribute in input text in vuejs?)
(2) In addition, there was a DOM timing re-rendering issue that I was having. The DOM was not updating when I tried to toggle back.
Upon certain situations, "the component will not re-render immediately. It will update in the next 'tick.'"
From Vue.js docs: https://vuejs.org/v2/guide/reactivity.html
The solution was to use:
this.$nextTick(()=>{
this.disableInputBool = true
})
Fuller example workflow:
<div @click="allowInputOverwrite">
<input
type="text"
:disabled="disableInputBool">
</div>
<button @click="disallowInputOverwrite">
press me (do stuff in method, then disable input bool again)
</button>
<script>
export default {
data() {
return {
disableInputBool: true
}
},
methods: {
allowInputOverwrite(){
this.disableInputBool = false
},
disallowInputOverwrite(){
// accomplish other stuff here.
this.$nextTick(()=>{
this.disableInputBool = true
})
}
}
}
</script>
When I installed nodemon using : npm install nodemon -g --save
, my path for the global npm packages was not present in the PATH variable .
If you just add it to the $PATH variable it will get fixed.
Edit the ~/.bashrc
file in your home folder and add this line :-
export PATH=$PATH:~/npm
Here "npm" is the path to my global npm packages . Replace it with the global path in your system
START
NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setDelegate:self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
UInt32 doChangeDefaultRoute = 1;
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof(doChangeDefaultRoute), &doChangeDefaultRoute);
NSError *error = nil;
NSString *filename = [NSString stringWithFormat:@"%@.caf",FILENAME];
NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:filename];
NSURL *soundFileURL = [NSURL fileURLWithPath:path];
NSDictionary *recordSettings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt: kAudioFormatMPEG4AAC], AVFormatIDKey,
[NSNumber numberWithInt:AVAudioQualityMedium],AVEncoderAudioQualityKey,
[NSNumber numberWithInt:AVAudioQualityMedium], AVSampleRateConverterAudioQualityKey,
[NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
[NSNumber numberWithFloat:22050.0],AVSampleRateKey,
nil];
AVAudioRecorder *audioRecorder = [[AVAudioRecorder alloc]
initWithURL:soundFileURL
settings:recordSettings
error:&error];
if (!error && [audioRecorder prepareToRecord])
{
[audioRecorder record];
}
STOP
[audioRecorder stop];
[audioRecorder release];
audioRecorder = nil;
You might want to check out this tutorial: http://www.webdesignerwall.com/tutorials/css-decorative-gallery/
In it the writer uses an empty span element to add an overlaying image. You can use jQuery to inject said span elements, if you'd like to keep your code as clean as possible. An example is also given in the aforementioned article.
Hope this helps!
-Dave
Just as Brian said, you can use remote debugging:
mvn exec:exec -Dexec.executable="java" -Dexec.args="-classpath %classpath -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=1044 com.mycompany.app.App"
Then in your eclipse, you can use remote debugging and attach the debugger to localhost:1044.
You're already doing it!
save()
will check if something in the model has changed. If it hasn't it won't run a db query.
Here's the relevant part of code in Illuminate\Database\Eloquent\Model@performUpdate
:
protected function performUpdate(Builder $query, array $options = [])
{
$dirty = $this->getDirty();
if (count($dirty) > 0)
{
// runs update query
}
return true;
}
The getDirty()
method simply compares the current attributes with a copy saved in original
when the model is created. This is done in the syncOriginal()
method:
public function __construct(array $attributes = array())
{
$this->bootIfNotBooted();
$this->syncOriginal();
$this->fill($attributes);
}
public function syncOriginal()
{
$this->original = $this->attributes;
return $this;
}
If you want to check if the model is dirty just call isDirty()
:
if($product->isDirty()){
// changes have been made
}
Or if you want to check a certain attribute:
if($product->isDirty('price')){
// price has changed
}
Follow these steps:
Regular expression
option near the bottom of the dialog.To add a word, such as test
, at the beginning of each line:
- Type
^
in theFind what
textbox- Type
test
in theReplace with
textbox- Place cursor in the first line of the file to ensure all lines are affected
- Click
Replace All
button
To add a word, such as test
, at the end of each line:
- Type
$
in theFind what
textbox- Type
test
in theReplace with
textbox- Place cursor in the first line of the file to ensure all lines are affected
- Click
Replace All
button
With jQuery 1.6 version you can use the .promise()
method.
$(selector).fadeOut('slow');
$(selector).promise().done(function(){
// will be called when all the animations on the queue finish
});
I needed to drop a table and re-create with a data from a view. I was creating a table out of a view and this is what I did:
DROP TABLE <table_name>;
CREATE TABLE <table_name> AS SELECT * FROM <view>;
The above worked for me using MySQL MariaDb.
Run "cmd.exe" as administrator and then run "sc.exe" to add a new Windows service.
for example:
sc.exe create MongoDB binPath= "c:\program files\mongodb\server\3.2\bin\mongod.exe"
It's all about performance and development speed. Of course, if you are a good programmer and design something that is really tailored to your needs, you might achieve better performance than if you had used a Javascript framework. But do you have the time to do it all by yourself?
My personal opinion is that Javascript is incredibly useful and overused, but that if you really need it, a framework is the way to go.
Now comes the choice of the framework. For what benchmarks are worth, you can find one at http://ejohn.org/files/142/ . It also depends on which plugins are available and what you intend to do with them. I started using jQuery because it seemed to be maintained and well featured, even though it wasn't the fastest at that moment. I do not regret it but I didn't test anything else since then.
If you want to copy a source directory entirely with the same directory structure, Then don't use a star(*). Write COPY command in Dockerfile as below.
COPY . destinatio-directory/
We were having the same issues on our jenkins slaves (linux machine) and tried all the options above.
The only thing helped is setting the argument
chrome_options.add_argument('--headless')
But when we investigated further, noticed that XVFB screen doesn't started property and thats causing this error. After we fix XVFB screen, it resolved the issue.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar;
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_drawer,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_drawer){
drawerLayout.openDrawer(GravityCompat.END);
if (drawerLayout.isDrawerOpen(GravityCompat.END)) {
drawerLayout.closeDrawer(GravityCompat.END);
} else {
drawerLayout.openDrawer(GravityCompat.END);
}
}
return super.onOptionsItemSelected(item);
}
res/layout/drawer_menu
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_drawer"
android:title="@string/app_name"
android:icon="@drawable/ic_menu_black_24dp"
app:showAsAction="always"/>
</menu>
toolbar.xml
<com.google.android.material.appbar.AppBarLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay"
app:titleTextColor="@android:color/white"
app:titleTextAppearance="@style/TextAppearance.Widget.Event.Toolbar.Title">
<TextView
android:id="@+id/toolbar_title"
android:layout_gravity="center"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/app_name"
android:textColor="@android:color/white"
style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title" />
</androidx.appcompat.widget.Toolbar>
If you want to set the form's back color to some arbitrary RGB value, you can do this:
this.BackColor = Color.FromArgb(255, 232, 232); // this should be pink-ish
This Worked for me. For getting the latest code from master to my branch
git rebase origin/master
DateTime.Date
cannot be converted to SQL. Use EntityFunctions.TruncateTime method to get date part.
var eventsCustom = eventCustomRepository
.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference)
.Where(x => EntityFunctions.TruncateTime(x.DateTimeStart) == currentDate.Date);
UPDATE: As @shankbond mentioned in comments, in Entity Framework 6 EntityFunctions
is obsolete, and you should use DbFunctions
class, which is shipped with Entity Framework.
Try this, I tested to access JMX inside docker container
-Dcom.sun.management.jmxremote=true -Djava.rmi.server.hostname=localhost -Dcom.sun.management.jmxremote.port=16000 -Dcom.sun.management.jmxremote.rmi.port=16000 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false
Then
$ jconsole localhost:16000
This script outputs the number of unique values in each column of a given file. It assumes that first line of given file is header line. There is no need for defining number of fields. Simply save the script in a bash file (.sh) and provide the tab delimited file as a parameter to this script.
Code
#!/bin/bash
awk '
(NR==1){
for(fi=1; fi<=NF; fi++)
fname[fi]=$fi;
}
(NR!=1){
for(fi=1; fi<=NF; fi++)
arr[fname[fi]][$fi]++;
}
END{
for(fi=1; fi<=NF; fi++){
out=fname[fi];
for (item in arr[fname[fi]])
out=out"\t"item"_"arr[fname[fi]][item];
print(out);
}
}
' $1
Execution Example:
bash> ./script.sh <path to tab-delimited file>
Output Example
isRef A_15 C_42 G_24 T_18
isCar YEA_10 NO_40 NA_50
isTv FALSE_33 TRUE_66
if (System.IO.File.Exists(@"C:\test.txt"))
System.IO.File.Delete(@"C:\test.txt"));
but
System.IO.File.Delete(@"C:\test.txt");
will do the same as long as the folder exists.
Supports entering y|ye|yes and case insensitive.
switch -regex ($someString.ToLower()) {
"^y(es?)?$" {
"You entered Yes."
}
default { "You entered No." }
}
A different approach ... here is an example: If the user has a delay of 600-1000ms when is typing you may consider he's stopped.
myEditText.addTextChangedListener(new TextWatcher() {_x000D_
_x000D_
private String s;_x000D_
private long after;_x000D_
private Thread t;_x000D_
private Runnable runnable_EditTextWatcher = new Runnable() {_x000D_
@Override_x000D_
public void run() {_x000D_
while (true) {_x000D_
if ((System.currentTimeMillis() - after) > 600)_x000D_
{_x000D_
Log.d("Debug_EditTEXT_watcher", "(System.currentTimeMillis()-after)>600 -> " + (System.currentTimeMillis() - after) + " > " + s);_x000D_
// Do your stuff_x000D_
t = null;_x000D_
break;_x000D_
}_x000D_
}_x000D_
}_x000D_
};_x000D_
_x000D_
@Override_x000D_
public void onTextChanged(CharSequence ss, int start, int before, int count) {_x000D_
s = ss.toString();_x000D_
}_x000D_
_x000D_
@Override_x000D_
public void beforeTextChanged(CharSequence s, int start, int count, int after) {_x000D_
}_x000D_
_x000D_
@Override_x000D_
public void afterTextChanged(Editable ss) {_x000D_
after = System.currentTimeMillis();_x000D_
if (t == null)_x000D_
{_x000D_
t = new Thread(runnable_EditTextWatcher);_x000D_
t.start();_x000D_
}_x000D_
}_x000D_
});
_x000D_
After enabling Two Factor Authentication (2FA), you may see something like this when attempting to use git clone
, git fetch
, git pull
or git push
:
$ git push origin master
Username for 'https://github.com': your_user_name
Password for 'https://[email protected]':
remote: Invalid username or password.
fatal: Authentication failed for 'https://github.com/your_user_name/repo_name.git/'
From the GitHub Help documentation:
After 2FA is enabled you will need to enter a personal access token instead of a 2FA code and your GitHub password.
...
For example, when you access a repository using Git on the command line using commands like
git clone
,git fetch
,git pull
orgit push
with HTTPS URLs, you must provide your GitHub username and your personal access token when prompted for a username and password. The command line prompt won't specify that you should enter your personal access token when it asks for your password.
Related question: https://stackoverflow.com/a/21374369/101662
I think I was trying something very similar to the original poster. the get() worked for me, although the name inside the chart was not inherited. Here is the code that worked for me.
#install it if you dont have it
library(quantmod)
# a list of stock tickers
myStocks <- c("INTC", "AAPL", "GOOG", "LTD")
# get some stock prices from default service
getSymbols(myStocks)
# to pause in between plots
par(ask=TRUE)
# plot all symbols
for (i in 1:length(myStocks)) {
chartSeries(get(myStocks[i]), subset="last 26 weeks")
}
The default schema for the user could be changed with the following query and avoids changing the property every time a table is to be created.
USE [DBName]
GO
ALTER USER [YourUserName] WITH DEFAULT_SCHEMA = [YourSchema]
GO
This should work:
start "" "c:\program files\php\php.exe" D:\mydocs\mp\index.php param1 param2
The start
command interprets the first argument as a window title if it contains spaces. In this case, that means start
considers your whole argument a title and sees no command. Passing ""
(an empty title) as the first argument to start
fixes the problem.
Simple Solution, just type the below:
conda update pandas
Type this in your preferred shell (on Windows, use Anaconda Prompt as administrator).
You can compare element height and element height with line-height: 0
function lineCount(elm) {
const style = elm.getAttribute('style')
elm.style.marginTop = 0
elm.style.marginBottom = 0
elm.style.paddingTop = 0
elm.style.paddingBottom = 0
const heightAllLine = elm.offsetHeight
elm.style.lineHeight = 0
const height1line = elm.offsetHeight
const lineCount = Math.round(heightAllLine / height1line)
elm.setAttribute('style', style)
if (isNaN(lineCount)) return 0
return lineCount
}
microbenchmark
is a lightweight (~50kB) package and more-or-less a standard way in R for benchmarking multiple expressions and functions:
microbenchmark(myfunction(with,arguments))
For example:
> microbenchmark::microbenchmark(log10(5), log(5)/log(10), times = 10000)
Unit: nanoseconds
expr min lq mean median uq max neval cld
log10(5) 0 0 25.5738 0 1 10265 10000 a
log(5)/log(10) 0 0 28.1838 0 1 10265 10000
Here both the expressions were evaluated 10000 times, with mean execution time being around 25-30 ns.
To fill a list with seperate instances of a class, you can use a for loop in the declaration of the list. The * multiply will link each copy to the same instance.
instancelist = [ MyClass() for i in range(29)]
and then access the instances through the index of the list.
instancelist[5].attr1 = 'whamma'
In Eclipse, I had to use New > Other > JUnit > Junit Test
. A Java class created with the exact same text gave me the error, perhaps because it was using JUnit 3.x.
You could use a template like :
#include <iostream>
using std::cerr;
using std::endl;
//qt4type
typedef unsigned int quint32;
template <typename T>
void deletep(T &) {}
template <typename T>
void deletep(T* & ptr) {
delete ptr;
ptr = 0;
}
template<typename T>
class Matrix {
public:
typedef T value_type;
Matrix() : _cols(0), _rows(0), _data(new T[0]), auto_delete(true) {};
Matrix(quint32 rows, quint32 cols, bool auto_del = true);
bool exists(quint32 row, quint32 col) const;
T & operator()(quint32 row, quint32 col);
T operator()(quint32 row, quint32 col) const;
virtual ~Matrix();
int size() const { return _rows * _cols; }
int rows() const { return _rows; }
int cols() const { return _cols; }
private:
Matrix(const Matrix &);
quint32 _rows, _cols;
mutable T * _data;
const bool auto_delete;
};
template<typename T>
Matrix<T>::Matrix(quint32 rows, quint32 cols, bool auto_del) : _rows(rows), _cols(cols), auto_delete(auto_del) {
_data = new T[rows * cols];
}
template<typename T>
inline T & Matrix<T>::operator()(quint32 row, quint32 col) {
return _data[_cols * row + col];
}
template<typename T>
inline T Matrix<T>::operator()(quint32 row, quint32 col) const {
return _data[_cols * row + col];
}
template<typename T>
bool Matrix<T>::exists(quint32 row, quint32 col) const {
return (row < _rows && col < _cols);
}
template<typename T>
Matrix<T>::~Matrix() {
if(auto_delete){
for(int i = 0, c = size(); i < c; ++i){
//will do nothing if T isn't a pointer
deletep(_data[i]);
}
}
delete [] _data;
}
int main() {
Matrix< int > m(10,10);
quint32 i = 0;
for(int x = 0; x < 10; ++x) {
for(int y = 0; y < 10; ++y, ++i) {
m(x, y) = i;
}
}
for(int x = 0; x < 10; ++x) {
for(int y = 0; y < 10; ++y) {
cerr << "@(" << x << ", " << y << ") : " << m(x,y) << endl;
}
}
}
*edit, fixed a typo.
You can update progress bar only from ProgressChanged
or RunWorkerCompleted
event handlers as these are synchronized with the UI thread.
The basic idea is. Thread.Sleep
just simulates some work here. Replace it with your real routing call.
public Form1()
{
InitializeComponent();
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
backgroundWorker1.WorkerReportsProgress = true;
}
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(1000);
backgroundWorker1.ReportProgress(i);
}
}
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
Step 1 : 5/7 = 0.71
Step 2 : Take the left side of the decimal , so we take 0 from 0.71 and multiply by 7 0*7 = 0;
Step # : 5-0 = 5 ; Therefore , 5%7 =5
In my case tomcat was configured to start not on localhost(guess it came from servers.xml connector entry) so Eclipse fails to find it running after start. Changed Host name
on Servers
tab to my 192.168.xxx.yyy
ip.
Had the same error message, though tomcat did start sucessfully, but then Eclipse shuts it down.
To round a double in Dart to a given degree of precision AFTER the decimal point, you can use built-in solution in dart toStringAsFixed()
method, but you have to convert it back to double
void main() {
double step1 = 1/3;
print(step1); // 0.3333333333333333
String step2 = step1.toStringAsFixed(2);
print(step2); // 0.33
double step3 = double.parse(step2);
print(step3); // 0.33
}
The issue is that you're not saving the mysqli connection. Change your connect to:
$aVar = mysqli_connect('localhost','tdoylex1_dork','dorkk','tdoylex1_dork');
And then include it in your query:
$query1 = mysqli_query($aVar, "SELECT name1 FROM users
ORDER BY RAND()
LIMIT 1");
$aName1 = mysqli_fetch_assoc($query1);
$name1 = $aName1['name1'];
Also don't forget to enclose your connections variables as strings as I have above. This is what's causing the error but you're using the function wrong, mysqli_query returns a query object but to get the data out of this you need to use something like mysqli_fetch_assoc http://php.net/manual/en/mysqli-result.fetch-assoc.php to actually get the data out into a variable as I have above.
The base64 encoding of Content-Type: multipart/form-data
adds an extra 33% overhead. If the server supports it, it is more efficient to send the files directly:
$scope.upload = function(url, file) {
var config = { headers: { 'Content-Type': undefined },
transformResponse: angular.identity
};
return $http.post(url, file, config);
};
When sending a POST with a File object, it is important to set 'Content-Type': undefined
. The XHR send method will then detect the File object and automatically set the content type.
To send multiple files, see Doing Multiple $http.post
Requests Directly from a FileList
I figured I should start with input type="file", but then found out that AngularJS can't bind to that..
The <input type=file>
element does not by default work with the ng-model directive. It needs a custom directive:
ng-model
1angular.module("app",[]);
angular.module("app").directive("selectNgFiles", function() {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
})
}
}
});
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
<h1>AngularJS Input `type=file` Demo</h1>
<input type="file" select-ng-files ng-model="fileArray" multiple>
<h2>Files</h2>
<div ng-repeat="file in fileArray">
{{file.name}}
</div>
</body>
_x000D_
$http.post
with content type multipart/form-data
If one must send multipart/form-data
:
<form role="form" enctype="multipart/form-data" name="myForm">
<input type="text" ng-model="fdata.UserName">
<input type="text" ng-model="fdata.FirstName">
<input type="file" select-ng-files ng-model="filesArray" multiple>
<button type="submit" ng-click="upload()">save</button>
</form>
$scope.upload = function() {
var fd = new FormData();
fd.append("data", angular.toJson($scope.fdata));
for (i=0; i<$scope.filesArray.length; i++) {
fd.append("file"+i, $scope.filesArray[i]);
};
var config = { headers: {'Content-Type': undefined},
transformRequest: angular.identity
}
return $http.post(url, fd, config);
};
When sending a POST with the FormData API, it is important to set 'Content-Type': undefined
. The XHR send method will then detect the FormData
object and automatically set the content type header to multipart/form-data with the proper boundary.
The compiler replaces null comparisons with a call to HasValue
, so there is no real difference. Just do whichever is more readable/makes more sense to you and your colleagues.
I solved a lot of issues by using the following code. Issues were : -
const sequelize = new Sequelize("test", "root", "root", {
host: "127.0.0.1",
dialect: "mysql",
port: "8889",
connectionLimit: 10,
socketPath: "/Applications/MAMP/tmp/mysql/mysql.sock",
// It will disable logging
logging: false
});
For visualization and summary of PyTorch
models, tensorboardX can also can be utilized.
If one or both of the files you wish to compare isn't in an Eclipse project:
Open the Quick Access search box
Type compare and select Compare With Other Resource
Select the files to compare ? OK
You can also create a keyboard shortcut for Compare With Other Resource by going to Window ? Preferences ? General ? Keys
I had a list of dataframes with no common id column.
I had missing data on many dfs. There were Null values.
The dataframes were produced using table function.
The Reduce, Merging, rbind, rbind.fill, and their like could not help me to my aim.
My aim was to produce an understandable merged dataframe, irrelevant of the missing data and common id column.
Therefore, I made the following function. Maybe this function can help someone.
##########################################################
#### Dependencies #####
##########################################################
# Depends on Base R only
##########################################################
#### Example DF #####
##########################################################
# Example df
ex_df <- cbind(c( seq(1, 10, 1), rep("NA", 0), seq(1,10, 1) ),
c( seq(1, 7, 1), rep("NA", 3), seq(1, 12, 1) ),
c( seq(1, 3, 1), rep("NA", 7), seq(1, 5, 1), rep("NA", 5) ))
# Making colnames and rownames
colnames(ex_df) <- 1:dim(ex_df)[2]
rownames(ex_df) <- 1:dim(ex_df)[1]
# Making an unequal list of dfs,
# without a common id column
list_of_df <- apply(ex_df=="NA", 2, ( table) )
it is following the function
##########################################################
#### The function #####
##########################################################
# The function to rbind it
rbind_null_df_lists <- function ( list_of_dfs ) {
length_df <- do.call(rbind, (lapply( list_of_dfs, function(x) length(x))))
max_no <- max(length_df[,1])
max_df <- length_df[max(length_df),]
name_df <- names(length_df[length_df== max_no,][1])
names_list <- names(list_of_dfs[ name_df][[1]])
df_dfs <- list()
for (i in 1:max_no ) {
df_dfs[[i]] <- do.call(rbind, lapply(1:length(list_of_dfs), function(x) list_of_dfs[[x]][i]))
}
df_cbind <- do.call( cbind, df_dfs )
rownames( df_cbind ) <- rownames (length_df)
colnames( df_cbind ) <- names_list
df_cbind
}
Running the example
##########################################################
#### Running the example #####
##########################################################
rbind_null_df_lists ( list_of_df )
This solution is for Litespeed Server (Apache as well)
Add the following code in .htaccess
RewriteRule .* - [E=noabort:1]
RewriteRule .* - [E=noconntimeout:1]
String input = "GATATATGCG";
String substring = "G";
String temp = input;
String indexOF ="";
int tempIntex=1;
while(temp.indexOf(substring) != -1)
{
int index = temp.indexOf(substring);
indexOF +=(index+tempIntex)+" ";
tempIntex+=(index+1);
temp = temp.substring(index + 1);
}
Log.e("indexOf ","" + indexOF);
This is along the lines of Lawrence Wenham's answer, but depending on your use case, it may or may not be an improvement -- you don't need the setters.
public interface IPerson {
int GetAge();
string GetName();
}
public interface IGetPerson {
IPerson GetPerson();
}
public static class IGetPersonAdditions {
public static int GetAgeViaPerson(this IGetPerson getPerson) { // I prefer to have the "ViaPerson" in the name in case the object has another Age property.
IPerson person = getPerson.GetPersion();
return person.GetAge();
}
public static string GetNameViaPerson(this IGetPerson getPerson) {
return getPerson.GetPerson().GetName();
}
}
public class Person: IPerson, IGetPerson {
private int Age {get;set;}
private string Name {get;set;}
public IPerson GetPerson() {
return this;
}
public int GetAge() { return Age; }
public string GetName() { return Name; }
}
Now any object that knows how to get a person can implement IGetPerson, and it will automatically have the GetAgeViaPerson() and GetNameViaPerson() methods. From this point, basically all Person code goes into IGetPerson, not into IPerson, other than new ivars, which have to go into both. And in using such code, you don't have to be concerned about whether or not your IGetPerson object is itself actually an IPerson.
Before to check the array, do this:
if(!is_array($memcachedConfig))
$memcachedConfig = array();
From Koshke's work on ggplot2 and his blog (Koshke's blog)
... + theme(legend.key.height=unit(3,"line")) # Change 3 to X
... + theme(legend.key.width=unit(3,"line")) # Change 3 to X
Type theme_get()
in the console to see other editable legend attributes.
I had this same question a while back and came across one of Scott Hanselman's posts:
Implementing HTTP File Upload with ASP.NET MVC including Tests and Mocks
Hope this helps.