dtype('O')
inside dataframe this means Pandas string.What is dtype
?
Something that belongs to pandas
or numpy
, or both, or something else? If we examine pandas code:
df = pd.DataFrame({'float': [1.0],
'int': [1],
'datetime': [pd.Timestamp('20180310')],
'string': ['foo']})
print(df)
print(df['float'].dtype,df['int'].dtype,df['datetime'].dtype,df['string'].dtype)
df['string'].dtype
It will output like this:
float int datetime string
0 1.0 1 2018-03-10 foo
---
float64 int64 datetime64[ns] object
---
dtype('O')
You can interpret the last as Pandas dtype('O')
or Pandas object which is Python type string, and this corresponds to Numpy string_
, or unicode_
types.
Pandas dtype Python type NumPy type Usage
object str string_, unicode_ Text
Like Don Quixote is on ass, Pandas is on Numpy and Numpy understand the underlying architecture of your system and uses the class numpy.dtype
for that.
Data type object is an instance of numpy.dtype
class that understand the data type more precise including:
In the context of this question dtype
belongs to both pands and numpy and in particular dtype('O')
means we expect the string.
Here is some code for testing with explanation: If we have the dataset as dictionary
import pandas as pd
import numpy as np
from pandas import Timestamp
data={'id': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}, 'date': {0: Timestamp('2018-12-12 00:00:00'), 1: Timestamp('2018-12-12 00:00:00'), 2: Timestamp('2018-12-12 00:00:00'), 3: Timestamp('2018-12-12 00:00:00'), 4: Timestamp('2018-12-12 00:00:00')}, 'role': {0: 'Support', 1: 'Marketing', 2: 'Business Development', 3: 'Sales', 4: 'Engineering'}, 'num': {0: 123, 1: 234, 2: 345, 3: 456, 4: 567}, 'fnum': {0: 3.14, 1: 2.14, 2: -0.14, 3: 41.3, 4: 3.14}}
df = pd.DataFrame.from_dict(data) #now we have a dataframe
print(df)
print(df.dtypes)
The last lines will examine the dataframe and note the output:
id date role num fnum
0 1 2018-12-12 Support 123 3.14
1 2 2018-12-12 Marketing 234 2.14
2 3 2018-12-12 Business Development 345 -0.14
3 4 2018-12-12 Sales 456 41.30
4 5 2018-12-12 Engineering 567 3.14
id int64
date datetime64[ns]
role object
num int64
fnum float64
dtype: object
All kind of different dtypes
df.iloc[1,:] = np.nan
df.iloc[2,:] = None
But if we try to set np.nan
or None
this will not affect the original column dtype. The output will be like this:
print(df)
print(df.dtypes)
id date role num fnum
0 1.0 2018-12-12 Support 123.0 3.14
1 NaN NaT NaN NaN NaN
2 NaN NaT None NaN NaN
3 4.0 2018-12-12 Sales 456.0 41.30
4 5.0 2018-12-12 Engineering 567.0 3.14
id float64
date datetime64[ns]
role object
num float64
fnum float64
dtype: object
So np.nan
or None
will not change the columns dtype
, unless we set the all column rows to np.nan
or None
. In that case column will become float64
or object
respectively.
You may try also setting single rows:
df.iloc[3,:] = 0 # will convert datetime to object only
df.iloc[4,:] = '' # will convert all columns to object
And to note here, if we set string inside a non string column it will become string or object dtype
.
This is not exactly a hot topic, but I have a factory class that allows a dll to create an instance and return it as a DLL. It is what I came looking for but couldn't find exactly.
It is called like,
IHTTP_Server *server = SN::SN_Factory<IHTTP_Server>::CreateObject();
IHTTP_Server *server2 =
SN::SN_Factory<IHTTP_Server>::CreateObject(IHTTP_Server_special_entry);
where IHTTP_Server is the pure virtual interface for a class created either in another DLL, or the same one.
DEFINE_INTERFACE is used to give a class id an interface. Place inside interface;
An interface class looks like,
class IMyInterface
{
DEFINE_INTERFACE(IMyInterface);
public:
virtual ~IMyInterface() {};
virtual void MyMethod1() = 0;
...
};
The header file is like this
#if !defined(SN_FACTORY_H_INCLUDED)
#define SN_FACTORY_H_INCLUDED
#pragma once
The libraries are listed in this macro definition. One line per library/executable. It would be cool if we could call into another executable.
#define SN_APPLY_LIBRARIES(L, A) \
L(A, sn, "sn.dll") \
L(A, http_server_lib, "http_server_lib.dll") \
L(A, http_server, "")
Then for each dll/exe you define a macro and list its implementations. Def means that it is the default implementation for the interface. If it is not the default, you give a name for the interface used to identify it. Ie, special, and the name will be IHTTP_Server_special_entry.
#define SN_APPLY_ENTRYPOINTS_sn(M) \
M(IHTTP_Handler, SNI::SNI_HTTP_Handler, sn, def) \
M(IHTTP_Handler, SNI::SNI_HTTP_Handler, sn, special)
#define SN_APPLY_ENTRYPOINTS_http_server_lib(M) \
M(IHTTP_Server, HTTP::server::server, http_server_lib, def)
#define SN_APPLY_ENTRYPOINTS_http_server(M)
With the libraries all setup, the header file uses the macro definitions to define the needful.
#define APPLY_ENTRY(A, N, L) \
SN_APPLY_ENTRYPOINTS_##N(A)
#define DEFINE_INTERFACE(I) \
public: \
static const long Id = SN::I##_def_entry; \
private:
namespace SN
{
#define DEFINE_LIBRARY_ENUM(A, N, L) \
N##_library,
This creates an enum for the libraries.
enum LibraryValues
{
SN_APPLY_LIBRARIES(DEFINE_LIBRARY_ENUM, "")
LastLibrary
};
#define DEFINE_ENTRY_ENUM(I, C, L, D) \
I##_##D##_entry,
This creates an enum for interface implementations.
enum EntryValues
{
SN_APPLY_LIBRARIES(APPLY_ENTRY, DEFINE_ENTRY_ENUM)
LastEntry
};
long CallEntryPoint(long id, long interfaceId);
This defines the factory class. Not much to it here.
template <class I>
class SN_Factory
{
public:
SN_Factory()
{
}
static I *CreateObject(long id = I::Id )
{
return (I *)CallEntryPoint(id, I::Id);
}
};
}
#endif //SN_FACTORY_H_INCLUDED
Then the CPP is,
#include "sn_factory.h"
#include <windows.h>
Create the external entry point. You can check that it exists using depends.exe.
extern "C"
{
__declspec(dllexport) long entrypoint(long id)
{
#define CREATE_OBJECT(I, C, L, D) \
case SN::I##_##D##_entry: return (int) new C();
switch (id)
{
SN_APPLY_CURRENT_LIBRARY(APPLY_ENTRY, CREATE_OBJECT)
case -1:
default:
return 0;
}
}
}
The macros set up all the data needed.
namespace SN
{
bool loaded = false;
char * libraryPathArray[SN::LastLibrary];
#define DEFINE_LIBRARY_PATH(A, N, L) \
libraryPathArray[N##_library] = L;
static void LoadLibraryPaths()
{
SN_APPLY_LIBRARIES(DEFINE_LIBRARY_PATH, "")
}
typedef long(*f_entrypoint)(long id);
f_entrypoint libraryFunctionArray[LastLibrary - 1];
void InitlibraryFunctionArray()
{
for (long j = 0; j < LastLibrary; j++)
{
libraryFunctionArray[j] = 0;
}
#define DEFAULT_LIBRARY_ENTRY(A, N, L) \
libraryFunctionArray[N##_library] = &entrypoint;
SN_APPLY_CURRENT_LIBRARY(DEFAULT_LIBRARY_ENTRY, "")
}
enum SN::LibraryValues libraryForEntryPointArray[SN::LastEntry];
#define DEFINE_ENTRY_POINT_LIBRARY(I, C, L, D) \
libraryForEntryPointArray[I##_##D##_entry] = L##_library;
void LoadLibraryForEntryPointArray()
{
SN_APPLY_LIBRARIES(APPLY_ENTRY, DEFINE_ENTRY_POINT_LIBRARY)
}
enum SN::EntryValues defaultEntryArray[SN::LastEntry];
#define DEFINE_ENTRY_DEFAULT(I, C, L, D) \
defaultEntryArray[I##_##D##_entry] = I##_def_entry;
void LoadDefaultEntries()
{
SN_APPLY_LIBRARIES(APPLY_ENTRY, DEFINE_ENTRY_DEFAULT)
}
void Initialize()
{
if (!loaded)
{
loaded = true;
LoadLibraryPaths();
InitlibraryFunctionArray();
LoadLibraryForEntryPointArray();
LoadDefaultEntries();
}
}
long CallEntryPoint(long id, long interfaceId)
{
Initialize();
// assert(defaultEntryArray[id] == interfaceId, "Request to create an object for the wrong interface.")
enum SN::LibraryValues l = libraryForEntryPointArray[id];
f_entrypoint f = libraryFunctionArray[l];
if (!f)
{
HINSTANCE hGetProcIDDLL = LoadLibraryA(libraryPathArray[l]);
if (!hGetProcIDDLL) {
return NULL;
}
// resolve function address here
f = (f_entrypoint)GetProcAddress(hGetProcIDDLL, "entrypoint");
if (!f) {
return NULL;
}
libraryFunctionArray[l] = f;
}
return f(id);
}
}
Each library includes this "cpp" with a stub cpp for each library/executable. Any specific compiled header stuff.
#include "sn_pch.h"
Setup this library.
#define SN_APPLY_CURRENT_LIBRARY(L, A) \
L(A, sn, "sn.dll")
An include for the main cpp. I guess this cpp could be a .h. But there are different ways you could do this. This approach worked for me.
#include "../inc/sn_factory.cpp"
Programatically this can be achieved with SCHTASKS:
SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=1074)]]" /EC Security /tn on_shutdown_normal /tr "c:\some.bat"
SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=6006)]]" /EC Security /tn on_shutdown_6006 /tr "c:\some.bat"
SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=6008)]]" /EC Security /tn on_shutdown_6008 /tr "c:\some.bat"
You could try:
print ''.join(ch for ch in some_string if ch.isalnum())
To go up a directory in a link, use ..
. This means "go up one directory", so your link will look something like this:
<a href="../index.html">Home</a>
Just to propose a sed
alternative. :) To skip first one million lines, try |sed '1,1000000d'
.
Example:
$ perl -wle 'print for (1..1_000_005)'|sed '1,1000000d'
1000001
1000002
1000003
1000004
1000005
If you want to avoid adding extra dependencies, I found node's process.argv
to be useful:
gulp.task('mytask', function() {
console.log(process.argv);
});
So the following:
gulp mytask --option 123
should display:
[ 'node', 'path/to/gulp.js', 'mytask', '--option', '123']
If you are sure that the desired parameter is in the right position, then the flags aren't needed.** Just use (in this case):
var option = process.argv[4]; //set to '123'
BUT: as the option may not be set, or may be in a different position, I feel that a better idea would be something like:
var option, i = process.argv.indexOf("--option");
if(i>-1) {
option = process.argv[i+1];
}
That way, you can handle variations in multiple options, like:
//task should still find 'option' variable in all cases
gulp mytask --newoption somestuff --option 123
gulp mytask --option 123 --newoption somestuff
gulp mytask --flag --option 123
** Edit: true for node scripts, but gulp interprets anything without a leading "--" as another task name. So using gulp mytask 123
will fail because gulp can't find a task called '123'.
You can use SVG for rounding corners and load into an ImageView and use ConstraintLayout to bring ImageView on TextView
I used it for rounded ImageView and rounded TextView
Just check for it before you pass to your function. So you would pass:
thing.foo ? thing.foo.bar : undefined
I mentioned this in a comment on the other question, but the whole idea of Inversion of Control is to have none of your classes know or care how they get the objects they depend on. This makes it easy to change what type of implementation of a given dependency you use at any time. It also makes the classes easy to test, as you can provide mock implementations of dependencies. Finally, it makes the classes simpler and more focused on their core responsibility.
Calling ApplicationContext.getBean()
is not Inversion of Control! While it's still easy to change what implemenation is configured for the given bean name, the class now relies directly on Spring to provide that dependency and can't get it any other way. You can't just make your own mock implementation in a test class and pass that to it yourself. This basically defeats Spring's purpose as a dependency injection container.
Everywhere you want to say:
MyClass myClass = applicationContext.getBean("myClass");
you should instead, for example, declare a method:
public void setMyClass(MyClass myClass) {
this.myClass = myClass;
}
And then in your configuration:
<bean id="myClass" class="MyClass">...</bean>
<bean id="myOtherClass" class="MyOtherClass">
<property name="myClass" ref="myClass"/>
</bean>
Spring will then automatically inject myClass
into myOtherClass
.
Declare everything in this way, and at the root of it all have something like:
<bean id="myApplication" class="MyApplication">
<property name="myCentralClass" ref="myCentralClass"/>
<property name="myOtherCentralClass" ref="myOtherCentralClass"/>
</bean>
MyApplication
is the most central class, and depends at least indirectly on every other service in your program. When bootstrapping, in your main
method, you can call applicationContext.getBean("myApplication")
but you should not need to call getBean()
anywhere else!
Sometimes you don't control the target machine (e.g. your library needs to run on a locked-down enterprise system). In such a case you will need to recompile your code using the version of GCC that corresponds to their GLIBCXX version. In that case, you can do the following:
strings /usr/lib/libstdc++.so.6 | grep GLIBC
... Say the version is 3.4.19
.[4.8.3, 4.9.0)
.I'm aware the question is php
oriented, but the best way to redirect a POST
request is probably using .htaccess
, ie:
RewriteEngine on
RewriteCond %{REQUEST_URI} string_to_match_in_url
RewriteCond %{REQUEST_METHOD} POST
RewriteRule ^(.*)$ https://domain.tld/$1 [L,R=307]
Explanation:
By default, if you want to redirect request with POST data, browser redirects it via GET with 302 redirect
. This also drops all the POST data associated with the request. Browser does this as a precaution to prevent any unintentional re-submitting of POST transaction.
But what if you want to redirect anyway POST request with it’s data? In HTTP 1.1, there is a status code for this. Status code 307
indicates that the request should be repeated with the same HTTP method and data. So your POST request will be repeated along with it’s data if you use this status code.
You can do this with a single statement - assuming you are calling it from a JDBC-like connector with in/out parameters functionality:
insert into batch(batchid, batchname)
values (batch_seq.nextval, 'new batch')
returning batchid into :l_batchid;
or, as a pl-sql script:
variable l_batchid number;
insert into batch(batchid, batchname)
values (batch_seq.nextval, 'new batch')
returning batchid into :l_batchid;
select :l_batchid from dual;
I just want to mention a thing, there are many tools can do text processing, e.g. sort, cut, split, join, paste, comm, uniq, column, rev, tac, tr, nl, pr, head, tail.....
they are very handy but you have to learn their options etc.
A lazy way (not the best way) to learn text processing might be: only learn grep , sed and awk. with this three tools, you can solve almost 99% of text processing problems and don't need to memorize above different cmds and options. :)
AND, if you 've learned and used the three, you knew the difference. Actually, the difference here means which tool is good at solving what kind of problem.
a more lazy way might be learning a script language (python, perl or ruby) and do every text processing with it.
You can use CSS3 'transform':
CSS:
.popup-bck{
background-color: rgba(102, 102, 102, .5);
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
z-index: 10;
}
.popup-content-box{
background-color: white;
position: fixed;
top: 50%;
left: 50%;
z-index: 11;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
HTML:
<div class="popup-bck"></div>
<div class="popup-content-box">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</div>
*so you don't have to use margin-left: -width/2 px;
You could move the common parts to another configuration file and include
from both server contexts. This should work:
server {
listen 80;
server_name server1.example;
...
include /etc/nginx/include.d/your-common-stuff.conf;
}
server {
listen 80;
server_name another-one.example;
...
include /etc/nginx/include.d/your-common-stuff.conf;
}
Edit: Here's an example that's actually copied from my running server. I configure my basic server settings in /etc/nginx/sites-enabled
(normal stuff for nginx on Ubuntu/Debian). For example, my main server bunkus.org
's configuration file is /etc/nginx/sites-enabled
and it looks like this:
server {
listen 80 default_server;
listen [2a01:4f8:120:3105::101:1]:80 default_server;
include /etc/nginx/include.d/all-common;
include /etc/nginx/include.d/bunkus.org-common;
include /etc/nginx/include.d/bunkus.org-80;
}
server {
listen 443 default_server;
listen [2a01:4f8:120:3105::101:1]:443 default_server;
include /etc/nginx/include.d/all-common;
include /etc/nginx/include.d/ssl-common;
include /etc/nginx/include.d/bunkus.org-common;
include /etc/nginx/include.d/bunkus.org-443;
}
As an example here's the /etc/nginx/include.d/all-common
file that's included from both server
contexts:
index index.html index.htm index.php .dirindex.php;
try_files $uri $uri/ =404;
location ~ /\.ht {
deny all;
}
location = /favicon.ico {
log_not_found off;
access_log off;
}
location ~ /(README|ChangeLog)$ {
types { }
default_type text/plain;
}
First of all get the height of the view yo want to saw and make a boolean to save if the view is showing:
int heigth=0;
boolean showing=false;
LinearLayout layout = (LinearLayout) view.findViewById(R.id.layout);
proDetailsLL.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// gets called after layout has been done but before display
// so we can get the height then hide the view
proHeight = proDetailsLL.getHeight(); // Ahaha! Gotcha
proDetailsLL.getViewTreeObserver().removeGlobalOnLayoutListener(this);
proDetailsLL.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 0));
}
});
Then call the method for showing hide the view, and change the value of the boolean:
slideInOutAnimation(showing, heigth, layout);
proShowing = !proShowing;
The method:
/**
* Method to slide in out the layout
*
* @param isShowing
* if the layout is showing
* @param height
* the height to slide
* @param slideLL
* the container to show
*/
private void slideInOutAnimation(boolean isShowing, int height, final LinearLayout slideLL, final ImageView arroIV) {
if (!isShowing) {
Animation animIn = new Animation() {
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
// Do relevant calculations here using the interpolatedTime that runs from 0 to 1
slideLL.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int) (heigth * interpolatedTime)));
}
};
animIn.setDuration(500);
slideLL.startAnimation(animIn);
} else {
Animation animOut = new Animation() {
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
// Do relevant calculations here using the interpolatedTime that runs from 0 to 1
slideLL.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
(int) (heigth * (1 - interpolatedTime))));
}
};
animOut.setDuration(500);
slideLL.startAnimation(animOut);
}
}
I'm assuming you mean a datetime picker in a winforms application.
in your code, you can do the following:
string theDate = dateTimePicker1.Value.ToShortDateString();
or, if you'd like to specify the format of the date:
string theDate = dateTimePicker1.Value.ToString("yyyy-MM-dd");
Adding to Alex's answer and simplifying it:
Objects are more strict with their use and hence gives the programmer more compile time "evaluation" power and hence in a lot of cases provide more "checking capability" and coould prevent any leaks, whereas any is a more generic term and a lot of compile time checks might hence be ignored.
Simpler and a Standard solution to increment the number and to retain the dot at the end. Even if you get the css right, it will not work if your HTML is not correct. see below.
ol {
counter-reset: item;
}
ol li {
display: block;
}
ol li:before {
content: counters(item, ". ") ". ";
counter-increment: item;
}
ol {
counter-reset: item;
li {
display: block;
&:before {
content: counters(item, ". ") ". ";
counter-increment: item
}
}
}
If you add the child make sure the it is under the parent li
.
<!-- WRONG -->
<ol>
<li>Parent 1</li> <!-- Parent is Individual. Not hugging -->
<ol>
<li>Child</li>
</ol>
<li>Parent 2</li>
</ol>
<!-- RIGHT -->
<ol>
<li>Parent 1
<ol>
<li>Child</li>
</ol>
</li> <!-- Parent is Hugging the child -->
<li>Parent 2</li>
</ol>
If you're on a page and this does not work:
$page_object = get_queried_object();
$page_id = get_queried_object_id();
you can try to build the permalink manually with PHP so you can lookup the post ID:
// get or make permalink
$url = !empty(get_the_permalink()) ? get_the_permalink() : (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$permalink = strtok($url, '?');
// get post_id using url/permalink
$post_id = url_to_postid($url);
// want the post or postmeta? use get_post() or get_post_meta()
$post = get_post($post_id);
$postmeta = get_post_meta($post_id);
It may not catch every possible permalink (especially since I'm stripping out the query string), but you can modify it to fit your use case.
If Ragnar
's answer doesn't work for you. Here is probably why (based on my experience) -
I wasn't using node-mysql
package as shown my Ragnar
. I was using mysql
package. They're different (if you didn't notice - just like me). But I'm not sure if it has anything to do with the ?
not working, since it seemed to work for many folks using the mysql
package.
Try using a variable instead of ?
The following worked for me -
var mysql = require('node-mysql');
var conn = mysql.createConnection({
...
});
var sql = "INSERT INTO Test (name, email, n) VALUES :params";
var values = [
['demian', '[email protected]', 1],
['john', '[email protected]', 2],
['mark', '[email protected]', 3],
['pete', '[email protected]', 4]
];
conn.query(sql, { params: values}, function(err) {
if (err) throw err;
conn.end();
});
Hope this helps someone.
I wanted a long dash like line, so I used this.
.dash{_x000D_
border: 1px solid red;_x000D_
width: 120px;_x000D_
height: 0px;_x000D_
_x000D_
}
_x000D_
<div class="dash"></div>
_x000D_
I came across this post and none of the solutions worked, so here is my solution that does work
Problems with other solutions thus far:
1) No explicit solution as to how the duration is modified
2) No solution for the out of order directory iteration, which is essential for GIFs
3) No explanation of how to install imageio for python 3
install imageio like this: python3 -m pip install imageio
Note: you'll want to make sure your frames have some sort of index in the filename so they can be sorted, otherwise you'll have no way of knowing where the GIF starts or ends
import imageio
import os
path = '/Users/myusername/Desktop/Pics/' # on Mac: right click on a folder, hold down option, and click "copy as pathname"
image_folder = os.fsencode(path)
filenames = []
for file in os.listdir(image_folder):
filename = os.fsdecode(file)
if filename.endswith( ('.jpeg', '.png', '.gif') ):
filenames.append(filename)
filenames.sort() # this iteration technique has no built in order, so sort the frames
images = list(map(lambda filename: imageio.imread(filename), filenames))
imageio.mimsave(os.path.join('movie.gif'), images, duration = 0.04) # modify duration as needed
string insertSql =
"INSERT INTO aspnet_GameProfiles(UserId,GameId) VALUES(@UserId, @GameId)SELECT SCOPE_IDENTITY()";
int primaryKey;
using (SqlConnection myConnection = new SqlConnection(myConnectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(insertSql, myConnection);
myCommand.Parameters.AddWithValue("@UserId", newUserId);
myCommand.Parameters.AddWithValue("@GameId", newGameId);
primaryKey = Convert.ToInt32(myCommand.ExecuteScalar());
myConnection.Close();
}
This will work.
What I learn about promises is to use it only as return values avoid referencing them if possible. async/await syntax is particularly practical for that. Today all latest browsers and node support it: https://caniuse.com/#feat=async-functions , is a simple behavior and the code is like reading synchronous code, forget about callbacks...
In cases I do need to reference a promises is when creation and resolution happen at independent/not-related places. So instead an artificial association and probably an event listener just to resolve the "distant" promise, I prefer to expose the promise as a Deferred, which the following code implements it in valid es5
/**
* Promise like object that allows to resolve it promise from outside code. Example:
*
```
class Api {
fooReady = new Deferred<Data>()
private knower() {
inOtherMoment(data=>{
this.fooReady.resolve(data)
})
}
}
```
*/
var Deferred = /** @class */ (function () {
function Deferred(callback) {
var instance = this;
this.resolve = null;
this.reject = null;
this.status = 'pending';
this.promise = new Promise(function (resolve, reject) {
instance.resolve = function () { this.status = 'resolved'; resolve.apply(this, arguments); };
instance.reject = function () { this.status = 'rejected'; reject.apply(this, arguments); };
});
if (typeof callback === 'function') {
callback.call(this, this.resolve, this.reject);
}
}
Deferred.prototype.then = function (resolve) {
return this.promise.then(resolve);
};
Deferred.prototype.catch = function (r) {
return this.promise.catch(r);
};
return Deferred;
}());
transpiled form a typescript project of mine:
For more complex cases I often use these guy small promise utilities without dependencies tested and typed. p-map has been useful several times. I think he covered most use cases:
https://github.com/sindresorhus?utf8=%E2%9C%93&tab=repositories&q=promise&type=source&language=
A simple approach would be to check how many digits are output by Integer.toHexString()
and add a leading zero to each byte if needed. Something like this:
public static String toHexString(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
I had this same issue and solved it by going to the file it was erroring on:
\repo\.git\refs\remotes\origin\master
This file was full of nulls, I replaced it with the latest ref from github.
I am using Android Studio 3.0 and was facing the same problem. I add this to my gradle:
multiDexEnabled true
And it worked!
Example
android {
compileSdkVersion 27
buildToolsVersion '27.0.1'
defaultConfig {
applicationId "com.xx.xxx"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
multiDexEnabled true //Add this
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
And clean the project.
Try the following
var original = 'www.test.com';
var stripped = original.substring(4);
This question is quite broad, so I'm going to give a couple of solutions.
Here's an example of using a Helper Method that you could change to fit your needs:
class SerializationHelper {
static toInstance<T>(obj: T, json: string) : T {
var jsonObj = JSON.parse(json);
if (typeof obj["fromJSON"] === "function") {
obj["fromJSON"](jsonObj);
}
else {
for (var propName in jsonObj) {
obj[propName] = jsonObj[propName]
}
}
return obj;
}
}
Then using it:
var json = '{"name": "John Doe"}',
foo = SerializationHelper.toInstance(new Foo(), json);
foo.GetName() === "John Doe";
Advanced Deserialization
This could also allow for some custom deserialization by adding your own fromJSON
method to the class (this works well with how JSON.stringify
already uses the toJSON
method, as will be shown):
interface IFooSerialized {
nameSomethingElse: string;
}
class Foo {
name: string;
GetName(): string { return this.name }
toJSON(): IFooSerialized {
return {
nameSomethingElse: this.name
};
}
fromJSON(obj: IFooSerialized) {
this.name = obj.nameSomethingElse;
}
}
Then using it:
var foo1 = new Foo();
foo1.name = "John Doe";
var json = JSON.stringify(foo1);
json === '{"nameSomethingElse":"John Doe"}';
var foo2 = SerializationHelper.toInstance(new Foo(), json);
foo2.GetName() === "John Doe";
Another way you could do this is by creating your own base class:
class Serializable {
fillFromJSON(json: string) {
var jsonObj = JSON.parse(json);
for (var propName in jsonObj) {
this[propName] = jsonObj[propName]
}
}
}
class Foo extends Serializable {
name: string;
GetName(): string { return this.name }
}
Then using it:
var foo = new Foo();
foo.fillFromJSON(json);
There's too many different ways to implement a custom deserialization using a base class so I'll leave that up to how you want it.
If you want something completely customizable, try out my solution here:
http://www.kevinwilliampang.com/post/Mapping-Enums-To-Strings-and-Strings-to-Enums-in-NET.aspx
Basically, the post outlines how to attach Description attributes to each of your enums and provides a generic way to map from enum to description.
package studRecords.one;
import java.util.List;
import java.util.Vector;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.net.ParseException;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class studRecords extends ListActivity
{
static String listName = "";
static String listUsn = "";
static Integer images;
private LayoutInflater layoutx;
private Vector<RowData> listValue;
RowData rd;
static final String[] names = new String[]
{
"Name (Stud1)", "Name (Stud2)",
"Name (Stud3)","Name (Stud4)"
};
static final String[] usn = new String[]
{
"1PI08CS016","1PI08CS007","1PI08CS017","1PI08CS047"
};
private Integer[] imgid =
{
R.drawable.stud1,R.drawable.stud2,R.drawable.stud3,
R.drawable.stud4
};
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mainlist);
layoutx = (LayoutInflater) getSystemService(
Activity.LAYOUT_INFLATER_SERVICE);
listValue = new Vector<RowData>();
for(int i=0;i<names.length;i++)
{
try
{
rd = new RowData(names[i],usn[i],i);
}
catch (ParseException e)
{
e.printStackTrace();
}
listValue.add(rd);
}
CustomAdapter adapter = new CustomAdapter(this, R.layout.list,
R.id.detail, listValue);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}
public void onListItemClick(ListView parent, View v, int position,long id)
{
listName = names[position];
listUsn = usn[position];
images = imgid[position];
Intent myIntent = new Intent();
Intent setClassName = myIntent.setClassName("studRecords.one","studRecords.one.nextList");
startActivity(myIntent);
}
private class RowData
{
protected String mNames;
protected String mUsn;
protected int mId;
RowData(String title,String detail,int id){
mId=id;
mNames = title;
mUsn = detail;
}
@Override
public String toString()
{
return mNames+" "+mUsn+" "+mId;
}
}
private class CustomAdapter extends ArrayAdapter<RowData>
{
public CustomAdapter(Context context, int resource,
int textViewResourceId, List<RowData> objects)
{
super(context, resource, textViewResourceId, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
TextView title = null;
TextView detail = null;
ImageView i11=null;
RowData rowData= getItem(position);
if(null == convertView)
{
convertView = layoutx.inflate(R.layout.list, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
i11=holder.getImage();
i11.setImageResource(imgid[rowData.mId]);
title = holder.gettitle();
title.setText(rowData.mNames);
detail = holder.getdetail();
detail.setText(rowData.mUsn);
return convertView;
}
private class ViewHolder
{
private View mRow;
private TextView title = null;
private TextView detail = null;
private ImageView i11=null;
public ViewHolder(View row)
{
mRow = row;
}
public TextView gettitle()
{
if(null == title)
{
title = (TextView) mRow.findViewById(R.id.title);
}
return title;
}
public TextView getdetail()
{
if(null == detail)
{
detail = (TextView) mRow.findViewById(R.id.detail);
}
return detail;
}
public ImageView getImage()
{
if(null == i11)
{
i11 = (ImageView) mRow.findViewById(R.id.img);
}
return i11;
}
}
}
}
//mainlist.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
try this one :
public void itemClicked(View v) {
//code to check if this checkbox is checked!
CheckBox checkBox = (CheckBox)v;
if(checkBox.isChecked()){
}
}
If you like Vim, it has built-in syntax highlighting for the syslog file, e.g. it will highlight error messages in red.
vi +'syntax on' /var/log/syslog
You can download IE Driver (both 32 and 64-bit) from Selenium official site: http://docs.seleniumhq.org/download/
IE Driver is also available in the following site:
from datetime import datetime
listA = range(10000000)
setA = set(listA)
tupA = tuple(listA)
#Source Code
def calc(data, type):
start = datetime.now()
if data in type:
print ""
end = datetime.now()
print end-start
calc(9999, listA)
calc(9999, tupA)
calc(9999, setA)
Output after comparing 10 iterations for all 3 : Comparison
You would use
List<List<String>> listOfLists = new ArrayList<List<String>>();
And then when you needed to add a new "row", you'd add the list:
listOfLists.add(new ArrayList<String>());
I've used this mostly when I wanted to hold references to several lists of Point in a GUI so I could draw multiple curves. It works well.
For example:
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
@SuppressWarnings("serial")
public class DrawStuff extends JPanel {
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
private static final Color POINTS_COLOR = Color.red;
private static final Color CURRENT_POINTS_COLOR = Color.blue;
private static final Stroke STROKE = new BasicStroke(4f);
private List<List<Point>> pointsList = new ArrayList<List<Point>>();
private List<Point> currentPointList = null;
public DrawStuff() {
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
addMouseListener(myMouseAdapter);
addMouseMotionListener(myMouseAdapter);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(STROKE);
g.setColor(POINTS_COLOR);
for (List<Point> pointList : pointsList) {
if (pointList.size() > 1) {
Point p1 = pointList.get(0);
for (int i = 1; i < pointList.size(); i++) {
Point p2 = pointList.get(i);
int x1 = p1.x;
int y1 = p1.y;
int x2 = p2.x;
int y2 = p2.y;
g.drawLine(x1, y1, x2, y2);
p1 = p2;
}
}
}
g.setColor(CURRENT_POINTS_COLOR);
if (currentPointList != null && currentPointList.size() > 1) {
Point p1 = currentPointList.get(0);
for (int i = 1; i < currentPointList.size(); i++) {
Point p2 = currentPointList.get(i);
int x1 = p1.x;
int y1 = p1.y;
int x2 = p2.x;
int y2 = p2.y;
g.drawLine(x1, y1, x2, y2);
p1 = p2;
}
}
}
private class MyMouseAdapter extends MouseAdapter {
@Override
public void mousePressed(MouseEvent mEvt) {
currentPointList = new ArrayList<Point>();
currentPointList.add(mEvt.getPoint());
repaint();
}
@Override
public void mouseDragged(MouseEvent mEvt) {
currentPointList.add(mEvt.getPoint());
repaint();
}
@Override
public void mouseReleased(MouseEvent mEvt) {
currentPointList.add(mEvt.getPoint());
pointsList.add(currentPointList);
currentPointList = null;
repaint();
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("DrawStuff");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new DrawStuff());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
You actually don't need a UIScrollView to do this. I used this code and it works for me:
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if (textField==_myTextField)
{
[self keyBoardAppeared];
}
return true;
}
-(void)textFieldDidEndEditing:(UITextField *)textField {
if (textField==_myTextField)
{
[self keyBoardDisappeared];
}
}
-(void) keyBoardAppeared
{
CGRect frame = self.view.frame;
[UIView animateWithDuration:0.3
delay:0
options: UIViewAnimationCurveEaseOut
animations:^{
self.view.frame = CGRectMake(frame.origin.x, frame.origin.y-215, frame.size.width, frame.size.height);
}
completion:^(BOOL finished){
}];
}
-(void) keyBoardDisappeared
{
CGRect frame = self.view.frame;
[UIView animateWithDuration:0.3
delay:0
options: UIViewAnimationCurveEaseOut
animations:^{
self.view.frame = CGRectMake(frame.origin.x, frame.origin.y+215, frame.size.width, frame.size.height);
}
completion:^(BOOL finished){
}];
}
You don't have the namespace the Login class is in as a reference.
Add the following to the form that uses the Login
class:
using FootballLeagueSystem;
When you want to use a class in another namespace, you have to tell the compiler where to find it. In this case, Login
is inside the FootballLeagueSystem
namespace, or : FootballLeagueSystem.Login
is the fully qualified namespace.
As a commenter pointed out, you declare the Login class inside the FootballLeagueSystem
namespace, but you're using it in the FootballLeague
namespace.
The fundamental difference between include
and import
is that you must use import
to refer to declarations or definitions that are in a different target namespace and you must use include
to refer to declarations or definitions that are (or will be) in the same target namespace.
Source: https://web.archive.org/web/20070804031046/http://xsd.stylusstudio.com/2002Jun/post08016.htm
Wrapping works but when you just want a space, I like:
<div class="col-xs-12" style="height:50px;"></div>
create or replace procedure point_triangle
AS
BEGIN
FOR thisteam in (select FIRSTNAME,LASTNAME,SUM(PTS) from PLAYERREGULARSEASON where TEAM = 'IND' group by FIRSTNAME, LASTNAME order by SUM(PTS) DESC)
LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.PTS);
END LOOP;
END;
/
select min(DEPARTMENT.DeptName) as deptname
from DEPARTMENT
inner join employee on
DEPARTMENT.DeptId = employee.DeptId
where Salary > 1000
group by (EmpId) having count(EmpId) > =2
try this one for centos 7 : service crond reload
Here you have simple example. Just remember to provide secretKey and siteKey from google api.
<?php
$siteKey = 'Provide element from google';
$secretKey = 'Provide element from google';
if($_POST['submit']){
$username = $_POST['username'];
$responseKey = $_POST['g-recaptcha-response'];
$userIP = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey&remoteip=$userIP";
$response = file_get_contents($url);
$response = json_decode($response);
if($response->success){
echo "Verification is correct. Your name is $username";
} else {
echo "Verification failed";
}
} ?>
<html>
<meta>
<title>Google ReCaptcha</title>
</meta>
<body>
<form action="index.php" method="post">
<input type="text" name="username" placeholder="Write your name"/>
<div class="g-recaptcha" data-sitekey="<?= $siteKey ?>"></div>
<input type="submit" name="submit" value="send"/>
</form>
<script src='https://www.google.com/recaptcha/api.js'></script>
</body>
The preferred way is to use a JavaScript library such as jQuery and set your data option as an object, then let jQuery do the encoding, like this:
$.ajax({
type: "POST",
url: "/link.json",
data: { value: poststr },
error: function(){ alert('some error occured'); }
});
If you can't use jQuery (which is pretty much the standard these days), use encodeURIComponent.
If the browser uses this attribute, it is only as an help for the user, so he won't upload a multi-megabyte file just to see it rejected by the server...
Same for the <input type="hidden" name="MAX_FILE_SIZE" value="100000">
tag: if the browser uses it, it won't send the file but an error resulting in UPLOAD_ERR_FORM_SIZE
(2) error in PHP (not sure how it is handled in other languages).
Note these are helps for the user. Of course, the server must always check the type and size of the file on its end: it is easy to tamper with these values on the client side.
You should use the Spring Boot Maven Plugin:
<project>
...
<build>
...
<plugins>
...
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.5.1.RELEASE</version>
<configuration>
<profiles>
<profile>foo</profile>
<profile>bar</profile>
</profiles>
</configuration>
...
</plugin>
...
</plugins>
...
</build>
...
</project>
How to DOWNLOAD a file after receiving it by AJAX
It’s convenient when the file is created for a long time and you need to show PRELOADER
Example when submitting a web form:
<script>
$(function () {
$('form').submit(function () {
$('#loader').show();
$.ajax({
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'binary',
xhrFields: {
'responseType': 'blob'
},
success: function(data, status, xhr) {
$('#loader').hide();
// if(data.type.indexOf('text/html') != -1){//If instead of a file you get an error page
// var reader = new FileReader();
// reader.readAsText(data);
// reader.onload = function() {alert(reader.result);};
// return;
// }
var link = document.createElement('a'),
filename = 'file.xlsx';
// if(xhr.getResponseHeader('Content-Disposition')){//filename
// filename = xhr.getResponseHeader('Content-Disposition');
// filename=filename.match(/filename="(.*?)"/)[1];
// filename=decodeURIComponent(escape(filename));
// }
link.href = URL.createObjectURL(data);
link.download = filename;
link.click();
}
});
return false;
});
});
</script>
Optional functional is commented out to simplify the example.
No need to create temporary files on the server.
On jQuery v2.2.4 OK. There will be an error on the old version:
Uncaught DOMException: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').
If you have multiple files and you don't want to have to type each file, I would recommend that you follow these simple steps (I am using clang-3.8
but you can use any other version):
generate all .ll
files
clang-3.8 -S -emit-llvm *.c
link them into a single one
llvm-link-3.8 -S -v -o single.ll *.ll
(Optional) Optimise your code (maybe some alias analysis)
opt-3.8 -S -O3 -aa -basicaaa -tbaa -licm single.ll -o optimised.ll
Generate assembly (generates a optimised.s
file)
llc-3.8 optimised.ll
Create executable (named a.out
)
clang-3.8 optimised.s
To move up a directory, the quickest way would be to add an alias to ~/.bash_profile
alias ..='cd ..'
and then one would need only to type '..[return]'.
A Transaction represents a unit of work with a database.
In spring TransactionDefinition
interface that defines Spring-compliant transaction properties. @Transactional
annotation describes transaction attributes on a method or class.
@Autowired
private TestDAO testDAO;
@Transactional(propagation=TransactionDefinition.PROPAGATION_REQUIRED,isolation=TransactionDefinition.ISOLATION_READ_UNCOMMITTED)
public void someTransactionalMethod(User user) {
// Interact with testDAO
}
Propagation (Reproduction) : is uses for inter transaction relation. (analogous to java inter thread communication)
+-------+---------------------------+------------------------------------------------------------------------------------------------------+
| value | Propagation | Description |
+-------+---------------------------+------------------------------------------------------------------------------------------------------+
| -1 | TIMEOUT_DEFAULT | Use the default timeout of the underlying transaction system, or none if timeouts are not supported. |
| 0 | PROPAGATION_REQUIRED | Support a current transaction; create a new one if none exists. |
| 1 | PROPAGATION_SUPPORTS | Support a current transaction; execute non-transactionally if none exists. |
| 2 | PROPAGATION_MANDATORY | Support a current transaction; throw an exception if no current transaction exists. |
| 3 | PROPAGATION_REQUIRES_NEW | Create a new transaction, suspending the current transaction if one exists. |
| 4 | PROPAGATION_NOT_SUPPORTED | Do not support a current transaction; rather always execute non-transactionally. |
| 5 | PROPAGATION_NEVER | Do not support a current transaction; throw an exception if a current transaction exists. |
| 6 | PROPAGATION_NESTED | Execute within a nested transaction if a current transaction exists. |
+-------+---------------------------+------------------------------------------------------------------------------------------------------+
Isolation : Isolation is one of the ACID (Atomicity, Consistency, Isolation, Durability) properties of database transactions. Isolation determines how transaction integrity is visible to other users and systems. It uses for resource locking i.e. concurrency control, make sure that only one transaction can access the resource at a given point.
Locking perception: isolation level determines the duration that locks are held.
+---------------------------+-------------------+-------------+-------------+------------------------+
| Isolation Level Mode | Read | Insert | Update | Lock Scope |
+---------------------------+-------------------+-------------+-------------+------------------------+
| READ_UNCOMMITTED | uncommitted data | Allowed | Allowed | No Lock |
| READ_COMMITTED (Default) | committed data | Allowed | Allowed | Lock on Committed data |
| REPEATABLE_READ | committed data | Allowed | Not Allowed | Lock on block of table |
| SERIALIZABLE | committed data | Not Allowed | Not Allowed | Lock on full table |
+---------------------------+-------------------+-------------+-------------+------------------------+
Read perception: the following 3 kinds of major problems occurs:
UPDATES
from another tx.INSERTS
and/or DELETES
from another txIsolation levels with different kinds of reads:
+---------------------------+----------------+----------------------+----------------+
| Isolation Level Mode | Dirty reads | Non-repeatable reads | Phantoms reads |
+---------------------------+----------------+----------------------+----------------+
| READ_UNCOMMITTED | allows | allows | allows |
| READ_COMMITTED (Default) | prevents | allows | allows |
| REPEATABLE_READ | prevents | prevents | allows |
| SERIALIZABLE | prevents | prevents | prevents |
+---------------------------+----------------+----------------------+----------------+
Use <a>
with href instead of a <button>
solves my problem.
<ion-nav-buttons side="secondary">
<a class="button icon-right ion-plus-round" href="#/app/gosomewhere"></a>
</ion-nav-buttons>
using (var cmd = new SqlCommand("SELECT EmpName FROM [Employee] WHERE EmpID = @id", con))
put []
around table name ;)
You aren't building your formula right.
Worksheets("EmployeeCosts").Range("B" & var1a).Formula = "=SUM(H5:H" & var1a & ")"
This does the same as the following lines do:
Dim myFormula As String
myFormula = "=SUM(H5:H"
myFormula = myFormula & var1a
myformula = myformula & ")"
which is what you are trying to do.
Also, you want to have the =
at the beginning of the formala.
I have same issue with IIS, i uninstalled IIS. Type in run services.msc, I see "wampapache64" service was not running, when I start it using right click it give me error.
I just used these steps.
Click on WAMP icon select Apache -> Service -> Remove Service
Click on Wamp icon select Apache -> Service -> Install Service
Got green Wamp icon :(
Here’s the JavaScript equivalent:
var i = null;
var j = i || 10; //j is now 10
Note that the logical operator ||
does not return a boolean value but the first value that can be converted to true.
Additionally use an array of objects instead of one single object:
var options = {
filters: [
{
name: 'firstName',
value: 'abc'
}
]
};
var filter = options.filters[0] || ''; // is {name:'firstName', value:'abc'}
var filter2 = options.filters[1] || ''; // is ''
That can be accessed by index.
Add commons-lang3-3.1.jar in your application build path. Use the below code snippet to trim the String array.
String array = {" String", "Tom Selleck "," Fish "};
array = StringUtils.stripAll(array);
First off, this is one of those things that slaps me in the face with surprise: renaming of a column requires creating an entirely new table and copying the data from the old table to the new table...
The GUI I've landed on to do SQLite operations is Base. It's got a nifty Log window that shows all the commands that have been executed. Doing a rename of a column via Base populates the log window with the necessary commands:
These can then be easily copied and pasted where you might need them. For me, that's into an ActiveAndroid migration file. A nice touch, as well, is that the copied data only includes the SQLite commands, not the timestamps, etc.
Hopefully, that saves some people time.
He is asking about the real difference. When you are talking about undefined behavior you are on the level of guarantee provided by language specification - it's far from reality. To understand the real difference please check this snippet (of course this is UB but it's perfectly defined on your favorite compiler):
#include <stdio.h>
int main()
{
int i1 = ~0;
int i2 = i1 >> 1;
unsigned u1 = ~0;
unsigned u2 = u1 >> 1;
printf("int : %X -> %X\n", i1, i2);
printf("unsigned int: %X -> %X\n", u1, u2);
}
Yes. Regardless of what anyone else says, Eclipse contains some bug(s) that sometimes causes the workspace setting (e.g. 1.6 compliant) to be ignored. This is even when the per-project settings are disabled, the workspace settings are correct (1.6), the JRE is correctly set, there is only a 1.6 JRE defined, etc., all the things that people generally recommend when questions about this issue are posted to various forums (as they often are).
We hit this irregularly, but often, and typically when there is some unrelated issue with build-time dependencies or other project issues. It seems to fall into the general category of "unable to get Eclipse to recognize reality" issues that I always attribute, rightly or wrongly, to refresh issues with Eclipse' extensive metadata. Eclipse metadata is a blessing and a curse; when all is working well, it makes the tool exceedingly powerful and fast. But when there are problems, the extensive caching makes straightening out the issues more difficult - sometimes much more difficult - than with other tools.
In Swift 4, if the image is returned as nil.
Click on image, on the right hand side (Utilities) -> Check Target Membership
http://sourceforge.net/projects/pywin32/files/ - 3rd .exe down
I know this thread has been idle for a while, but I just wanted to add my two cents to supplement jariq's comment...
Per manual, you don't necessary want to use -password
option.
Let's say mykey.key
has a password and your want to protect iphone-dev.p12
with another password, this is what you'd use:
pkcs12 -export -inkey mykey.key -in developer_identity.pem -out iphone_dev.p12 -passin pass:password_for_mykey -passout pass:password_for_iphone_dev
Have fun scripting!!
Edit Include path
Compiler path
Most probably it has to do with caching on the device. Catching the exception and ignoring is not nice but my problem was fixed and it seems to work.
Try this:
SELECT s.NAME + '.' + t.NAME AS TableName
FROM sys.tables t
INNER JOIN sys.schemas s
ON t.schema_id = s.schema_id
it will display the schema+table name for all tables in the current database.
Here is a version that will list every table in every database on the current server. it allows a search parameter to be used on any part or parts of the server+database+schema+table names:
SET NOCOUNT ON
DECLARE @AllTables table (CompleteTableName nvarchar(4000))
DECLARE @Search nvarchar(4000)
,@SQL nvarchar(4000)
SET @Search=null --all rows
SET @SQL='select @@SERVERNAME+''.''+''?''+''.''+s.name+''.''+t.name from [?].sys.tables t inner join sys.schemas s on t.schema_id=s.schema_id WHERE @@SERVERNAME+''.''+''?''+''.''+s.name+''.''+t.name LIKE ''%'+ISNULL(@SEARCH,'')+'%'''
INSERT INTO @AllTables (CompleteTableName)
EXEC sp_msforeachdb @SQL
SET NOCOUNT OFF
SELECT * FROM @AllTables ORDER BY 1
set @Search to NULL for all tables, set it to things like 'dbo.users' or 'users' or '.master.dbo' or even include wildcards like '.master.%.u', etc.
From ?read.table
: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.
So, perhaps your data file isn't clean. Being more specific will help the data import:
d = read.table("foobar.txt",
sep="\t",
col.names=c("id", "name"),
fill=FALSE,
strip.white=TRUE)
will specify exact columns and fill=FALSE
will force a two column data frame.
std::string the_string(c_string);
if(the_string.size() > max_length)
the_string.resize(max_length);
u could try this it produces randomly generated array of true and false :
a=[bool(i) for i in np.array(np.random.randint(0,2,10))]
out: [True, True, True, True, True, False, True, False, True, False]
Just add this npm script to the package.json
file in the root folder.
{
...
"scripts": {
...
"start": "react-scripts start", // or whatever else depends on your project
"dev": "(cd server && npm run start) & (cd ../client && npm run start)"
}
}
The following works. I may be mistaken but adding a String
value doesn't seem compatible to a DataGridView cell (I hadn't experimented or tried any hacks though).
DataGridViewName.Rows[0].Cells[0].Value = 1;
Instead of having to create a function in the ts file you can toggle a variable from the template itself. You can then use the variable to apply a specific class to the element. Like so-
<div (click)="status=!status"
[ngClass]="status ? 'success' : 'danger'">
Some content
</div>
So when status is true the class success is applied. When it is false danger class is applied.
This will work without any additional code in the ts file.
In my case, this was the best solution I found:
snprintf(str, sizeof str, "%s%c", str, c);
writelines()
does not add line separators. You can alter the list of strings by using map()
to add a new \n
(line break) at the end of each string.
items = ['abc', '123', '!@#']
items = map(lambda x: x + '\n', items)
w.writelines(items)
Yet another solution: Old DLLs pointing to each other and cached by Visual Studio in
C:\Users\[yourname]\AppData\Local\Microsoft\VisualStudio\10.0\ProjectAssemblies
Exit VS, delete everything in this folder and Bob's your uncle.
<
= less than <
, >
= greater than >
With CMake, it's generally recommended to do an "out of source" build. Create your CMakeLists.txt
in the root of your project. Then from the root of your project:
mkdir Release
cd Release
cmake -DCMAKE_BUILD_TYPE=Release ..
make
And for Debug
(again from the root of your project):
mkdir Debug
cd Debug
cmake -DCMAKE_BUILD_TYPE=Debug ..
make
Release
/ Debug
will add the appropriate flags for your compiler. There are also RelWithDebInfo
and MinSizeRel
build configurations.
You can modify/add to the flags by specifying a toolchain file in which you can add CMAKE_<LANG>_FLAGS_<CONFIG>_INIT
variables, e.g.:
set(CMAKE_CXX_FLAGS_DEBUG_INIT "-Wall")
set(CMAKE_CXX_FLAGS_RELEASE_INIT "-Wall")
See CMAKE_BUILD_TYPE for more details.
As for your third question, I'm not sure what you are asking exactly. CMake should automatically detect and use the compiler appropriate for your different source files.
The best of code and complete is here:
NumbersList.Exists(p => p.Equals(Input)
Use:
List<int> NumbersList = new List<int>();
private void button1_Click(object sender, EventArgs e)
{
int Input = Convert.ToInt32(textBox1.Text);
if (!NumbersList.Exists(p => p.Equals(Input)))
{
NumbersList.Add(Input);
}
else
{
MessageBox.Show("The number entered is in the list","Error");
}
}
Java doesn't have associative arrays, the closest thing you can get is the Map interface
Here's a sample from that page.
import java.util.*;
public class Freq {
public static void main(String[] args) {
Map<String, Integer> m = new HashMap<String, Integer>();
// Initialize frequency table from command line
for (String a : args) {
Integer freq = m.get(a);
m.put(a, (freq == null) ? 1 : freq + 1);
}
System.out.println(m.size() + " distinct words:");
System.out.println(m);
}
}
If run with:
java Freq if it is to be it is up to me to delegate
You'll get:
8 distinct words:
{to=3, delegate=1, be=1, it=2, up=1, if=1, me=1, is=2}
The $(document).ready mechanism is meant to fire after the DOM has been loaded successfully but makes no guarantees as to the state of the images referenced by the page.
When in doubt, fall back on the good ol' window.onload event:
window.onload = function()
{
//your code here
};
Now, this is obviously slower than the jQuery approach. However, you can compromise somewhere in between:
$(document).ready
(
function()
{
var img = document.getElementById("myImage");
var intervalId = setInterval(
function()
{
if(img.complete)
{
clearInterval(intervalId);
//now we can start rotating the header
}
},
50);
}
);
To explain a bit:
we grab the DOM element of the image whose image we want completely loaded
we then set an interval to fire every 50 milliseconds.
if, during one of these intervals, the complete attribute of this image is set to true, the interval is cleared and the rotate operation is safe to start.
Here's a little function that will do "NATO encoding" for you:
CREATE FUNCTION dbo.NATOEncode (
@String varchar(max)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN (
WITH L1 (N) AS (SELECT 1 UNION ALL SELECT 1),
L2 (N) AS (SELECT 1 FROM L1, L1 B),
L3 (N) AS (SELECT 1 FROM L2, L2 B),
L4 (N) AS (SELECT 1 FROM L3, L3 B),
L5 (N) AS (SELECT 1 FROM L4, L4 C),
L6 (N) AS (SELECT 1 FROM L5, L5 C),
Nums (Num) AS (SELECT Row_Number() OVER (ORDER BY (SELECT 1)) FROM L6)
SELECT
NATOString = Substring((
SELECT
Convert(varchar(max), ' ' + D.Word)
FROM
Nums N
INNER JOIN (VALUES
('A', 'Alpha'),
('B', 'Beta'),
('C', 'Charlie'),
('D', 'Delta'),
('E', 'Echo'),
('F', 'Foxtrot'),
('G', 'Golf'),
('H', 'Hotel'),
('I', 'India'),
('J', 'Juliet'),
('K', 'Kilo'),
('L', 'Lima'),
('M', 'Mike'),
('N', 'November'),
('O', 'Oscar'),
('P', 'Papa'),
('Q', 'Quebec'),
('R', 'Romeo'),
('S', 'Sierra'),
('T', 'Tango'),
('U', 'Uniform'),
('V', 'Victor'),
('W', 'Whiskey'),
('X', 'X-Ray'),
('Y', 'Yankee'),
('Z', 'Zulu'),
('0', 'Zero'),
('1', 'One'),
('2', 'Two'),
('3', 'Three'),
('4', 'Four'),
('5', 'Five'),
('6', 'Six'),
('7', 'Seven'),
('8', 'Eight'),
('9', 'Niner')
) D (Digit, Word)
ON Substring(@String, N.Num, 1) = D.Digit
WHERE
N.Num <= Len(@String)
FOR XML PATH(''), TYPE
).value('.[1]', 'varchar(max)'), 2, 2147483647)
);
This function will work on even very long strings, and performs pretty well (I ran it against a 100,000-character string and it returned in 589 ms). Here's an example of how to use it:
SELECT NATOString FROM dbo.NATOEncode('LD-23DSP-1430');
-- Output: Lima Delta Two Three Delta Sierra Papa One Four Three Zero
I intentionally made it a table-valued function so it could be inlined into a query if you run it against many rows at once, just use CROSS APPLY
or wrap the above example in parentheses to use it as a value in the SELECT
clause (you can put a column name in the function parameter position).
a[len(a):]
- This gets you the length of a to the end. It selects a range. If you reverse a[:len(a)]
it will get you the beginning to whatever is len(a)
.
Check if your activity layout overrides the theme, look for your activity layout located at layout/*your_activity*.xml
and look for TextView that contains android:textColor="(some hex code")
something like that on activity layout, and remove it. Then run your code again.
Sometimes you want to have your GridView as simple as:
<asp:GridView ID="grid" runat="server" />
You don't want to specify any BoundField, you just want to bind your grid to DataReader. The following code helped me to format DateTime in this situation.
protected void Page_Load(object sender, EventArgs e)
{
grid.RowDataBound += grid_RowDataBound;
// Your DB access code here...
// grid.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection);
// grid.DataBind();
}
void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow)
return;
var dt = (e.Row.DataItem as DbDataRecord).GetDateTime(4);
e.Row.Cells[4].Text = dt.ToString("dd.MM.yyyy");
}
The results shown here.
@ryenus, You need to loop through the result. This is how I'd do it in vbscript;
Set xmlDoc = CreateObject("Msxml2.DOMDocument")
xmlDoc.setProperty "SelectionLanguage", "XPath"
xmlDoc.load("kids.xml")
'Remove the id=1 attribute on Parent to return all child names for all Parent nodes
For Each c In xmlDoc.selectNodes ("//Parent[@id='1']/Children/child/@name")
Wscript.Echo c.text
Next
The modular crypt format for bcrypt consists of
$2$
, $2a$
or $2y$
identifying the hashing algorithm and format$
.
, /
, 0
–9
, A
–Z
, a
–z
that is different to the standard Base 64 Encoding alphabet) consisting of:
Thus the total length is 59 or 60 bytes respectively.
As you use the 2a format, you’ll need 60 bytes. And thus for MySQL I’ll recommend to use the CHAR(60) BINARY
or BINARY(60)
(see The _bin and binary Collations for information about the difference).
CHAR
is not binary safe and equality does not depend solely on the byte value but on the actual collation; in the worst case A
is treated as equal to a
. See The _bin
and binary
Collations for more information.
min(df['some_property'])
max(df['some_property'])
The built-in functions work well with Pandas Dataframes.
import cv2
import numpy as np
image_read = cv2.imread('filename.jpg',0)
original_image = np.asarray(image_read)
width , height = 452,452
resize_image = np.zeros(shape=(width,height))
for W in range(width):
for H in range(height):
new_width = int( W * original_image.shape[0] / width )
new_height = int( H * original_image.shape[1] / height )
resize_image[W][H] = original_image[new_width][new_height]
print("Resized image size : " , resize_image.shape)
cv2.imshow(resize_image)
cv2.waitKey(0)
I experienced this exception, and it was also related to ServicePointManager.SecurityProtocol
.
For me, this was because ServicePointManager.SecurityProtocol
had been set to Tls | Tls11
(because of certain websites the application visits with broken TLS 1.2) and upon visiting a TLS 1.2-only website (tested with SSLLabs' SSL Report), it failed.
An option for .NET 4.5 and higher is to enable all TLS versions:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12;
Everything in python is considered as object so functions are also objects. So you can use this method as well.
def fun1():
fun1.var = 100
print(fun1.var)
def fun2():
print(fun1.var)
fun1()
fun2()
print(fun1.var)
Use https://updates.jenkins-ci.org/download/plugins/. Download it from this central update repository for Jenkins.
Iterate over the grep results with a while/read loop. Like:
grep pattern filename.txt | while read -r line ; do
echo "Matched Line: $line"
# your code goes here
done
My answer does not require any additional libraries, and it's easy to understand. But you have to notice that if there's more than one number inside a string, my code will concatenate them together.
def search_number_string(string):
index_list = []
del index_list[:]
for i, x in enumerate(string):
if x.isdigit() == True:
index_list.append(i)
start = index_list[0]
end = index_list[-1] + 1
number = string[start:end]
return number
Try this
@font-face { _x000D_
src: url(fonts/Market_vilis.ttf) format("truetype");_x000D_
}_x000D_
div.FontMarket { _x000D_
font-family: Market Deco;_x000D_
}
_x000D_
<div class="FontMarket">KhonKaen Market</div>
_x000D_
vilis.org
I will add my answer since I don't use any of the other answers provided.
With the Support Library v7, all the styles are actually already defined and ready to use, for the standard buttons, all of these styles are available:
style="@style/Widget.AppCompat.Button"
style="@style/Widget.AppCompat.Button.Colored"
style="@style/Widget.AppCompat.Button.Borderless"
style="@style/Widget.AppCompat.Button.Borderless.Colored"
Widget.AppCompat.Button.Colored
:
Widget.AppCompat.Button.Borderless
Widget.AppCompat.Button.Borderless.Colored
:
To answer the question, the style to use is therefore
<Button style="@style/Widget.AppCompat.Button.Colored"
.......
.......
.......
android:text="Button"/>
For the whole app:
The color of all the UI controls (not only buttons, but also floating action buttons, checkboxes etc.) is managed by the attribute colorAccent
as explained here.
You can modify this style and apply your own color in your theme definition:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
...
<item name="colorAccent">@color/Orange</item>
</style>
For a specific button:
If you need to change the style of a specific button, you can define a new style, inheriting one of the parent styles described above. In the example below I just changed the background and font colors:
<style name="AppTheme.Button" parent="Widget.AppCompat.Button.Colored">
<item name="colorButtonNormal">@color/Red</item>
<item name="android:textColor">@color/White</item>
</style>
Then you just need to apply this new style on the button with:
android:theme="@style/AppTheme.Button"
To set a default button design in a layout, add this line to the styles.xml theme:
<item name="buttonStyle">@style/btn</item>
where @style/btn
is your button theme. This sets the button style for all the buttons in a layout with a specific theme
How about if you're copying each column in a sheet to different sheets? Example: row B of mysheet to row B of sheet1, row C of mysheet to row B of sheet 2...
The compiler is telling you that there are problems starting at line 122 in the middle of that strange FBI-CIA warning message. That message is not valid C++ code and is NOT commented out so of course it will cause compiler errors. Try removing that entire message.
Also, I agree with In silico: you should always tell us what you tried and exactly what error messages you got.
Try:
//Difference in days
var diff = Math.floor(( start - end ) / 86400000);
alert(diff);
I got sane error with LoginController, which I used in main index.html. I found two ways to resolve:
setting $controllerProvider.allowGlobals(), I found that comment in Angular change-list "this option might be handy for migrating old apps, but please don't use it in new ones!" original comment on Angular
app.config(['$controllerProvider', function($controllerProvider) { $controllerProvider.allowGlobals(); }]);
wrong contructor of registering controller
before
LoginController.$inject = ['$rootScope', '$scope', '$location'];
now
app.controller('LoginController', ['$rootScope', '$scope', '$location', LoginController]);
'app' come from app.js
var MyApp = {};
var app = angular.module('MyApp ', ['app.services']);
var services = angular.module('app.services', ['ngResource', 'ngCookies', 'ngAnimate', 'ngRoute']);
Don't use GridLayout for something it wasn't meant to do. It sounds to me like GridBagLayout would be a better fit for you, either that or MigLayout (though you'll have to download that first since it's not part of standard Java). Either that or combine layout managers such as BoxLayout for the lines and GridLayout to hold all the rows.
For example, using GridBagLayout:
import java.awt.*;
import javax.swing.*;
public class LayoutEg1 extends JPanel{
private static final int ROWS = 10;
public LayoutEg1() {
setLayout(new GridBagLayout());
for (int i = 0; i < ROWS; i++) {
GridBagConstraints gbc = makeGbc(0, i);
JLabel label = new JLabel("Row Label " + (i + 1));
add(label, gbc);
JPanel panel = new JPanel();
panel.add(new JCheckBox("check box"));
panel.add(new JTextField(10));
panel.add(new JButton("Button"));
panel.setBorder(BorderFactory.createEtchedBorder());
gbc = makeGbc(1, i);
add(panel, gbc);
}
}
private GridBagConstraints makeGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = x;
gbc.weighty = 1.0;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = (x == 0) ? GridBagConstraints.LINE_START : GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.HORIZONTAL;
return gbc;
}
private static void createAndShowUI() {
JFrame frame = new JFrame("Layout Eg1");
frame.getContentPane().add(new LayoutEg1());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
The ZERO WIDTH SPACE character is inserted when you use jQuery to add elements using DOM manipulation functions like .before() and .after()
I've run into this when adding hidden modal dialog frames at the end of my document and then finding that the ZERO WIDTH SPACE screws up the layout down there, adding unwanted space.
The quick fix was to insert it before the footer, not after it. Its hidden anyway.
I can't find anything in jQuery that does this:
https://github.com/jquery/jquery/blob/master/src/manipulation.js
So it might be the browser that adds it.
Node MergeLists(Node list1, Node list2) {
if (list1 == null) return list2;
if (list2 == null) return list1;
if (list1.data < list2.data) {
list1.next = MergeLists(list1.next, list2);
return list1;
} else {
list2.next = MergeLists(list2.next, list1);
return list2;
}
}
You can try this force-download script. Even if you don't use it, it'll probably point you in the right direction:
<?php
$filename = $_GET['file'];
// required for IE, otherwise Content-disposition is ignored
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
// addition by Jorg Weske
$file_extension = strtolower(substr(strrchr($filename,"."),1));
if( $filename == "" )
{
echo "<html><title>eLouai's Download Script</title><body>ERROR: download file NOT SPECIFIED. USE force-download.php?file=filepath</body></html>";
exit;
} elseif ( ! file_exists( $filename ) )
{
echo "<html><title>eLouai's Download Script</title><body>ERROR: File not found. USE force-download.php?file=filepath</body></html>";
exit;
};
switch( $file_extension )
{
case "pdf": $ctype="application/pdf"; break;
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "doc": $ctype="application/msword"; break;
case "xls": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
default: $ctype="application/octet-stream";
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: $ctype");
// change, added quotes to allow spaces in filenames, by Rajkumar Singh
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile("$filename");
exit();
As of npm@5
, the npm cache self-heals from corruption issues and data extracted from the cache is guaranteed to be valid. If you want to make sure everything is consistent, use npm cache verify
instead. On the other hand, if you're debugging an issue with the installer, you can use npm install --cache /tmp/empty-cache
to use a temporary cache instead of nuking the actual one.
If you're sure you want to delete the entire cache, rerun:
npm cache clean --force
A complete log of this run can be found in /Users/USERNAME/.npm/_logs/2019-01-08T21_29_30_811Z-debug.log
.
asp:HiddenField
as:
<asp:HiddenField runat="server" ID="hfProduct" ClientIDMode="Static" />
js code:
$("#hfProduct").val("test")
and the code behind:
hfProduct.Value.ToString();
In my case the issue was related to too long log outputting into IntelliJ IDEA console (OS windows 10).
Command:
mvn clean install
This command solved the issue to me:
mvn clean install > log-file.log
If you want to solve the general-case problem, and you can store and edit the array, then Caf's solution is by far the most efficient. If you can't store the array (streaming version), then sdcvvc's answer is the only type of solution currently suggested.
The solution I propose is the most efficient answer (so far on this thread) if you can store the problem but can't edit it, and I got the idea from Svalorzen's solution, which solves for 1 or 2 missing items. This solution takes T(k*n)
time and O(k)
and O(log(k))
space - with a possibility that it might actually be O(min(k,log(n)))
space. It also works well with parallelism.
The idea is that if you use the original approach of comparing sums:
int sum = SumOf(1,n) - SumOf(array)
... then you take the average of the missing numbers:
average = sum/array_size
... which provides a boundary: Of the missing numbers, there's guaranteed to be at least one number less-or-equal to average
, and at least one number greater than average
. This means that we can split into sub problems that each scan the array [O(n)
] and are only concerned with their respective sub-arrays.
C-style solution (don't judge me for the global variables, I'm just trying to make the code readable for non-c folks):
#include "stdio.h"
// Example problem:
const int array [] = {0, 7, 3, 1, 5};
const int N = 8; // size of original array
const int array_size = 5;
int SumOneTo (int n)
{
return n*(n-1)/2; // non-inclusive
}
int MissingItems (const int begin, const int end, int & average)
{
// We consider only sub-array where elements, e:
// begin <= e < end
// Initialise info about missing elements.
// First assume all are missing:
int n = end - begin;
int sum = SumOneTo(end) - SumOneTo(begin);
// Minus everything that we see (ie not missing):
for (int i = 0; i < array_size; ++i)
{
if ((begin <= array[i]) && (array[i] < end))
{
n -= 1;
sum -= array[i];
}
}
// used by caller:
average = sum/n;
return n;
}
void Find (const int begin, const int end)
{
int average;
if (MissingItems(begin, end, average) == 1)
{
printf(" %d", average); // average(n) is same as n
return;
}
Find(begin, average + 1); // at least one missing here
Find(average + 1, end); // at least one here also
}
int main ()
{
printf("Missing items:");
Find(0, N);
printf("\n");
}
Ignoring recursion for a moment, each function call clearly takes O(n)
time and O(1)
space. Note that sum
can equal as much as n(n-1)/2
, so requires double the amount of bits needed to store n-1
. At most this means than we effectively need two extra elements worth of space, regardless of the size of the array or k
, hence it's still O(1)
space under the normal conventions.
It's not so obvious how many function calls there are for k
missing elements, so I'll provide a visual. Your original sub-array (connected array) is the full array, which has all k
missing elements in it. We'll imagine them in increasing order, where --
represent connections (part of same sub-array):
m1 -- m2 -- m3 -- m4 -- (...) -- mk-1 -- mk
The effect of the Find
function is to disconnect the missing elements into different non-overlapping sub-arrays. It guarantees that there's at least one missing element in each sub-array, which means breaking exactly one connection.
What this means is that regardless of how the splits occur, it will always take k-1
Find
function calls to do the work of finding the sub-arrays that have only one missing element in it.
So the time complexity is T((k-1 + k) * n) = T(k*n)
.
For the space complexity, if we divide proportionally each time then we get O(log(k))
space complexity, but if we only separate one at a time it gives us O(k)
.
I actually suspect we the space complexity is a smaller O(min(k,log(n)))
, but it's harder to prove. My intuition: Where the average performs badly at separation is when there's an outlier, but because of this the separation then removes that outlier. In normal arrays, elements could all be exponentially different, but in this case they're all bound by n
.
You can use netcat for this.
nc ip port < /dev/null
connects to the server and directly closes the connection again. If netcat is not able to connect, it returns a non-zero exit code. The exit code is stored in the variable $?. As an example,
nc ip port < /dev/null; echo $?
will return 0 if and only if netcat could successfully connect to the port.
This question is a fairly difficult one. There is no real software limitation on the number of active connections a machine can have, though some OS's are more limited than others. The problem becomes one of resources. For example, let's say a single machine wants to support 64,000 simultaneous connections. If the server uses 1MB of RAM per connection, it would need 64GB of RAM. If each client needs to read a file, the disk or storage array access load becomes much larger than those devices can handle. If a server needs to fork one process per connection then the OS will spend the majority of its time context switching or starving processes for CPU time.
The C10K problem page has a very good discussion of this issue.
A robust Javascript library for capturing keyboard input and key combinations entered. It has no dependencies.
http://jaywcjlove.github.io/hotkeys/
hotkeys('enter,esc', function(event,handler){
switch(handler.key){
case "enter":$('.save').click();break;
case "esc":$('.cancel').click();break;
}
});
hotkeys understands the following modifiers: ?,shiftoption?altctrlcontrolcommand, and ?.
The following special keys can be used for shortcuts:backspacetab,clear,enter,return,esc,escape,space,up,down,left,right,home,end,pageup,pagedown,del,delete andf1 throughf19.
Another way to find all View:
SELECT DISTINCT table_name FROM information_schema.TABLES WHERE table_type = 'VIEW'
Lets consider this situation
class Animal {
void eat() {
System.out.println("animal : eat");
}
}
class Dog extends Animal {
void eat() {
System.out.println("dog : eat");
}
void anotherEat() {
super.eat();
}
}
public class Test {
public static void main(String[] args) {
Animal a = new Animal();
a.eat();
Dog d = new Dog();
d.eat();
d.anotherEat();
}
}
The output is going to be
animal : eat
dog : eat
animal : eat
The third line is printing "animal:eat" because we are calling super.eat()
. If we called this.eat()
, it would have printed as "dog:eat".
As of python 3.6 you can use Literal String Interpolation.
births = 5.25487
>>> print(f'If there was a birth every 7 seconds, there would be: {births:.2f} births')
If there was a birth every 7 seconds, there would be: 5.25 births
There's also an option to Auto Sync built-in in Aptana.
Very simple answer for this problem that seems to catch a lot of people:
<img src="url-to-image">
<p>Nullam id dolor id nibh ultricies vehicula ut id elit.</p>
img {
float: left;
}
p {
overflow: hidden;
}
See example: http://jsfiddle.net/vandigroup/upKGe/132/
I had this problem with an ASP.NET MVC app I was working on.
I realized I had recently changed my password, and I was able to fix it by logging out and logging back in again.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class BackgroundImageJFrame extends JFrame
{
JButton b1;
JLabel l1;
public BackgroundImageJFrame()
{
setTitle("Background Color for JFrame");
setSize(400,400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
/*
One way
-----------------*/
setLayout(new BorderLayout());
JLabel background=new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png"));
add(background);
background.setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
background.add(l1);
background.add(b1);
// Another way
setLayout(new BorderLayout());
setContentPane(new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads \\colorful design.png")));
setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
add(l1);
add(b1);
// Just for refresh :) Not optional!
setSize(399,399);
setSize(400,400);
}
public static void main(String args[])
{
new BackgroundImageJFrame();
}
}
Here's another way to plot the data, involves turning the date_time into an index, this might help you for future slicing
#convert column to datetime
trip_data['lpep_pickup_datetime'] = pd.to_datetime(trip_data['lpep_pickup_datetime'])
#turn the datetime to an index
trip_data.index = trip_data['lpep_pickup_datetime']
#Plot
trip_data['Trip_distance'].plot(kind='hist')
plt.show()
first, create a class to hold your parameters:
public class PkRk {
public int pk { get; set; }
public int rk { get; set; }
}
then, use the Html.Action
passing the parameters:
Html.Action("PkRkAction", new { pkrk = new PkRk { pk=400, rk=500} })
and use in Controller:
public ActionResult PkRkAction(PkRk pkrk) {
return PartialView(pkrk);
}
Make sure that you have the correct layout, and that the RecyclerView id is inside the layout. Otherwise, you will be getting this error. I had the same problem, then I noticed the layout was wrong.
public class ColorsFragment extends Fragment {
public ColorsFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
==> make sure you are getting the correct layout here. R.layout...
View rootView = inflater.inflate(R.layout.fragment_colors, container, false);
You can use the command split for this task. For example this command entered into the command prompt
split YourLogFile.txt -b 500m
creates several files with a size of 500 MByte each. This will take several minutes for a file of your size. You can rename the output files (by default called "xaa", "xab",... and so on) to *.txt to open it in the editor of your choice.
Make sure to check the help file for the command. You can also split the log file by number of lines or change the name of your output files.
(tested on Windows 7 64 bit)
you can write a stored procedure like this:
CREATE PROCEDURE sanitize_TABLE()
BEGIN
#replace space with underscore
UPDATE Table SET FieldName = REPLACE(FieldName," ","_") WHERE FieldName is not NULL;
#delete dot
UPDATE Table SET FieldName = REPLACE(FieldName,".","") WHERE FieldName is not NULL;
#delete (
UPDATE Table SET FieldName = REPLACE(FieldName,"(","") WHERE FieldName is not NULL;
#delete )
UPDATE Table SET FieldName = REPLACE(FieldName,")","") WHERE FieldName is not NULL;
#raplace or delete any char you want
#..........................
END
In this way you have modularized control over table.
You can also generalize stored procedure making it, parametric with table to sanitoze input parameter
Here is a simple approach which will print the 2 different elapsed time for each query.
DECLARE @t1 DATETIME;
DECLARE @t2 DATETIME;
SET @t1 = GETDATE();
SELECT DISTINCT u.profession FROM users u; --Query with DISTINCT
SET @t2 = GETDATE();
PRINT 'Elapsed time (ms): ' + CAST(DATEDIFF(millisecond, @t1, @t2) AS varchar);
SET @t1 = GETDATE();
SELECT u.profession FROM users u GROUP BY u.profession; --Query with GROUP BY
SET @t2 = GETDATE();
PRINT 'Elapsed time (ms): ' + CAST(DATEDIFF(millisecond, @t1, @t2) AS varchar);
OR try SET STATISTICS TIME (Transact-SQL)
SET STATISTICS TIME ON;
SELECT DISTINCT u.profession FROM users u; --Query with DISTINCT
SELECT u.profession FROM users u GROUP BY u.profession; --Query with GROUP BY
SET STATISTICS TIME OFF;
It simply displays the number of milliseconds required to parse, compile, and execute each statement as below:
SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 2 ms.
The best tool for doing layouts using grid, IMHO, is graph paper and a pencil. I know you're asking for some type of program, but it really does work. I've been doing Tk programming for a couple of decades so layout comes quite easily for me, yet I still break out graph paper when I have a complex GUI.
Another thing to think about is this: The real power of Tkinter geometry managers comes from using them together*. If you set out to use only grid, or only pack, you're doing it wrong. Instead, design your GUI on paper first, then look for patterns that are best solved by one or the other. Pack is the right choice for certain types of layouts, and grid is the right choice for others. For a very small set of problems, place is the right choice. Don't limit your thinking to using only one of the geometry managers.
* The only caveat to using both geometry managers is that you should only use one per container (a container can be any widget, but typically it will be a frame).
The standard equivalent of find -iname ... -exec mv -t dest {} +
for find
implementations that don't support -iname
or mv
implementations that don't support -t
is to use a shell to re-order the arguments:
find . -name '*.[cC][pP][pP]' -type f -exec sh -c '
exec mv "$@" /dest/dir/' sh {} +
By using -name '*.[cC][pP][pP]'
, we also avoid the reliance on the current locale to decide what's the uppercase version of c
or p
.
Note that +
, contrary to ;
is not special in any shell so doesn't need to be quoted (though quoting won't harm, except of course with shells like rc
that don't support \
as a quoting operator).
The trailing /
in /dest/dir/
is so that mv
fails with an error instead of renaming foo.cpp
to /dest/dir
in the case where only one cpp
file was found and /dest/dir
didn't exist or wasn't a directory (or symlink to directory).
if you want to check for the json empty case, we can directly use below code
String jsonString = {};
JSONObject jsonObject = new JSONObject(jsonString);
if(jsonObject.isEmpty()){
System.out.println("json is empty");
} else{
System.out.println("json is not empty");
}
this may help you.
If you have a list of lists, you only needed to use ...
import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)
per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.
Use window.confirm()
instead of window.alert()
.
HTML:
<input type="submit" onclick="return clicked();" value="Button" />
JavaScript:
function clicked() {
return confirm('clicked');
}
I solved it by renaming my function.
Changed
function editForm(value)
to
function editTheForm(value)
Works perfectly.
In most C-like languages I am deliberate about placing my braces where I think they make the code easiest to read.
PowerShell's parser recognizes when a statement clearly isn't complete, and looks to the next line. For example, imagine a cmdlet that takes an optional script block parameter:
Get-Foo { ............ }
if the script block is very long, you might want to write:
Get-Foo { ............... ............... ............... }
But this won't work: the parser will see two statements. The first is Get-Foo
and the second is a script block. Instead, I write:
Get-Foo { ............... ............... ............... }
I could use the line-continuation character (`) but that makes for hard-to-read code, and invites bugs.
Because this case requires the open brace to be on the previous line, I follow that pattern everywhere:
if (condition) { ..... }
Note that
if
statements require a script block in the language grammar, so the parser will look on the next line for the script block, but for consistency, I keep the open brace on the same line.
Simlarly, in the case of long pipelines, I break after the pipe character (|
):
$project.Items | ? { $_.Key -eq "ProjectFile" } | % { $_.Value } | % { $_.EvaluatedInclude } | % { ......... }
You've mentioned that they each have their own machines, but if they need to log onto a co-workers machine, and then use the file, saving it through "C:\Users\Public\Desktop\" will make it available to different usernames.
Public Sub SaveToDesktop()
ThisWorkbook.SaveAs Filename:="C:\Users\Public\Desktop\" & ThisWorkbook.Name & "_copy", _
FileFormat:=xlOpenXMLWorkbookMacroEnabled
End Sub
I'm not sure whether this would be a requirement, but may help!
To use Subversion in Visual Studio 2008, install TortoiseSVN and AnkhSVN.
TortoiseSVN is a really easy to use Revision control / version control / source control software for Windows. Since it's not an integration for a specific IDE you can use it with whatever development tools you like. TortoiseSVN is free to use. You don't need to get a loan or pay a full years salary to use it.
AnkhSVN is a Subversion SourceControl Provider for Visual Studio. The software allows you to perform the most common version control operations directly from inside the Microsoft Visual Studio IDE. With AnkhSVN you no longer need to leave your IDE to perform tasks like viewing the status of your source code, updating your Subversion working copy and committing changes. You can even browse your repository and you can plug-in your favorite diff tool.
You could make a method:
public byte[] toBytes(char[] data) {
byte[] toRet = new byte[data.length];
for(int i = 0; i < toRet.length; i++) {
toRet[i] = (byte) data[i];
}
return toRet;
}
Hope this helps
Value added:
Session.getInstance()
recommended over Session.getDefaultInstance()
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
public class Gmailer {
private static final Logger LOGGER = Logger.getLogger(Gmailer.class.getName());
public static void main(String[] args) {
send();
}
public static void send() {
Transport transport = null;
try {
String accountEmail = "[email protected]";
String accountAppPassword = "";
String displayName = "Display-Name ?";
String replyTo = "[email protected]";
String to = "[email protected]";
String cc = "[email protected]";
String bcc = "[email protected]";
String subject = "Subject ?";
String message = "<span style='color: red;'>?</span>";
String type = "html"; // or "plain"
String mimeTypeWithEncoding = "text/" + type + "; charset=" + StandardCharsets.UTF_8.name();
File attachmentFile = new File("Attachment.pdf");
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
String attachmentMimeType = "application/pdf";
byte[] bytes = ...; // read file to byte array
Properties properties = System.getProperties();
properties.put("mail.debug", "true");
// i found that this is the only property necessary for a modern java mail version
properties.put("mail.smtp.starttls.enable", "true");
// https://javaee.github.io/javamail/FAQ#getdefaultinstance
Session session = Session.getInstance(properties);
MimeMessage mimeMessage = new MimeMessage(session);
// probably best to use the account email address, to avoid landing in spam or blacklists
// not even sure if the server would accept a differing from address
InternetAddress from = new InternetAddress(accountEmail);
from.setPersonal(displayName, StandardCharsets.UTF_8.name());
mimeMessage.setFrom(from);
mimeMessage.setReplyTo(InternetAddress.parse(replyTo));
mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
mimeMessage.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
mimeMessage.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc));
mimeMessage.setSubject(subject, StandardCharsets.UTF_8.name());
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart messagePart = new MimeBodyPart();
messagePart.setContent(mimeMessage, mimeTypeWithEncoding);
multipart.addBodyPart(messagePart);
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.setDataHandler(new DataHandler(new ByteArrayDataSource(bytes, attachmentMimeType)));
attachmentPart.setFileName(attachmentFile.getName());
multipart.addBodyPart(attachmentPart);
mimeMessage.setContent(multipart);
transport = session.getTransport();
transport.connect("smtp.gmail.com", 587, accountEmail, accountAppPassword);
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
}
catch(Exception e) {
// I prefer to bubble up exceptions, so the caller has the info that someting went wrong, and gets a chance to handle it.
// I also prefer not to force the exception in the signature.
throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
}
finally {
if(transport != null) {
try {
transport.close();
}
catch(Exception e) {
LOGGER.log(Level.WARNING, "failed to close java mail transport: " + e);
}
}
}
}
}
I suggest using concat()
if you are using nodeJS. In all other cases, I have found that slice(0)
works fine.
I like the cardinality package for this, it is very lightweight and tries to use the fastest possible implementation available depending on the iterable.
Usage:
>>> import cardinality
>>> cardinality.count([1, 2, 3])
3
>>> cardinality.count(i for i in range(500))
500
>>> def gen():
... yield 'hello'
... yield 'world'
>>> cardinality.count(gen())
2
The actual count()
implementation is as follows:
def count(iterable):
if hasattr(iterable, '__len__'):
return len(iterable)
d = collections.deque(enumerate(iterable, 1), maxlen=1)
return d[0][0] if d else 0
This work for me, and I hope it will work for you also
Set the LayoutParams for the parent view first:
myTableLayout.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT,
TableLayout.LayoutParams.FILL_PARENT));
then set for the TextView (child):
TableLayout.LayoutParams textViewParam = new TableLayout.LayoutParams
(TableLayout.LayoutParams.WRAP_CONTENT,
TableLayout.LayoutParams.WRAP_CONTENT,1f);
//-- set components margins
textViewParam.setMargins(5, 0, 5,0);
myTextView.setLayoutParams(textViewParam);
You can pass data from PHP to javascript but the only way to get data from javascript to PHP is via AJAX.
The reason for that is you can build a valid javascript through PHP but to get data to PHP you will need to get PHP running again, and since PHP only runs to process the output, you will need a page reload or an asynchronous query.
It's a new year and there's a new mismatch between the version of protobuf
in Homebrew and the cutting edge release. As of February 2016, brew install protobuf
will give you version 2.6.1.
If you want the 3.0 beta release instead, you can install it with:
brew install --devel protobuf
@drop-shadow if you're using Hibernate, you can call Hibernate.initialize()
when you invoke the getStudents()
method:
Public class UniversityDaoImpl extends GenericDaoHibernate<University, Integer> implements UniversityDao {
//...
@Override
public University get(final Integer id) {
Query query = getQuery("from University u where idUniversity=:id").setParameter("id", id).setMaxResults(1).setFetchSize(1);
University university = (University) query.uniqueResult();
***Hibernate.initialize(university.getStudents());***
return university;
}
//...
}
You might want to do something like this (if you're in java 5 & up)
Scanner scanner = new Scanner(new File("tall.txt"));
int [] tall = new int [100];
int i = 0;
while(scanner.hasNextInt()){
tall[i++] = scanner.nextInt();
}
There is a comprehensive list of tools on the PostgreSQL Wiki:
https://wiki.postgresql.org/wiki/PostgreSQL_Clients
And of course PostgreSQL itself comes with pgAdmin, a GUI tool for accessing Postgres databases.
If the class is declared static, all of the members must be static too.
static NameValueCollection appSetting = ConfigurationManager.AppSettings;
Are you sure you want your employee class to be static? You almost certainly don't want that behaviour. You'd probably be better off removing the static constraint from the class and the members.
you can use DateUtils class in org.apache.commons.lang3.time package
int addMinuteTime = 5;
Date targetTime = new Date(); //now
targetTime = DateUtils.addMinutes(targetTime, addMinuteTime); //add minute
Look into the Dimensions plugin, specifically scrollTop()
/scrollLeft()
. Information can be found at http://api.jquery.com/scrollTop.
Adjusted to allow for daylight saving differences. try this:
function daysBetween(date1, date2) {
// adjust diff for for daylight savings
var hoursToAdjust = Math.abs(date1.getTimezoneOffset() /60) - Math.abs(date2.getTimezoneOffset() /60);
// apply the tz offset
date2.addHours(hoursToAdjust);
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24
// Convert both dates to milliseconds
var date1_ms = date1.getTime()
var date2_ms = date2.getTime()
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms)
// Convert back to days and return
return Math.round(difference_ms/ONE_DAY)
}
// you'll want this addHours function too
Date.prototype.addHours= function(h){
this.setHours(this.getHours()+h);
return this;
}
also be aware that if you are creating a array within a method, you cannot return it. If you return a pointer to it, it would have been removed from the stack when the function returns. you must allocate memory onto the heap and return a pointer to that. eg.
//this is bad
char* getname()
{
char name[100];
return name;
}
//this is better
char* getname()
{
char *name = malloc(100);
return name;
//remember to free(name)
}
To create elements with equal width using Flex
, you should set to your's child (flex elements):
flex-basis: 25%;
flex-grow: 0;
It will give to all elements in row 25% width. They will not grow and go one by one.
You can convert String to Timestamp:
String inDate = "01-01-1990"
DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
Timestamp ts = new Timestamp(((java.util.Date)df.parse(inDate)).getTime());
Try
html
<!-- placeholder ,
`click` download , `.remove()` options ,
at js callback , following js
-->
<a>download</a>
js
$(document).ready(function () {
$.ajax({
// `url`
url: '/echo/json/',
type: "POST",
dataType: 'json',
// `file`, data-uri, base64
data: {
json: JSON.stringify({
"file": "data:text/plain;base64,YWJj"
})
},
// `custom header`
headers: {
"x-custom-header": 123
},
beforeSend: function (jqxhr) {
console.log(this.headers);
alert("custom headers" + JSON.stringify(this.headers));
},
success: function (data) {
// `file download`
$("a")
.attr({
"href": data.file,
"download": "file.txt"
})
.html($("a").attr("download"))
.get(0).click();
console.log(JSON.parse(JSON.stringify(data)));
},
error: function (jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown)
}
});
});
Note for git submodule users - the solutions here will not work for you as-is.
Let's say you have a parent repository called dev
, for example, and your submodule repository is called api
.
if you are inside of api
and you get the error mentioned in this question:
error: bad index file sha1 signature
fatal: index file corrupt
The index
file will NOT be inside of a .git
folder. In fact, the .git
won't even be a folder - it will will be a text document with the location of the real .git data for this repository. Likely something like this:
~/dev/api $ cat .git
gitdir: ../.git/modules/api
So, instead of rm -f .git/index
, you will need to do this:
rm -f ../.git/modules/api/index
git reset
or, more generally,
rm -f ../.git/modules/INSERT_YOUR_REPO_NAME_HERE/index
git reset
Try This. You need pass the authentication to let the server know its a valid user. You need to import these two packages and has to include a jersy jar. If you dont want to include jersy jar then import this package
import sun.misc.BASE64Encoder;
import com.sun.jersey.core.util.Base64;
import sun.net.www.protocol.http.HttpURLConnection;
and then,
String encodedAuthorizedUser = getAuthantication("username", "password");
URL url = new URL("Your Valid Jira URL");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty ("Authorization", "Basic " + encodedAuthorizedUser );
public String getAuthantication(String username, String password) {
String auth = new String(Base64.encode(username + ":" + password));
return auth;
}
How about adding a space in the pattern attribute like pattern="[a-zA-Z0-9 ]+"
.
If you want to support any kind of space try pattern="[a-zA-Z0-9\s]+"
Just change these settings in the Solution Explorer.
MaximizeBox = False
MinimizeBox = False
The other things such as ControlBox, Locked, and FormBorderStyle are extra.
As Internet Explorer doesn't natively support rounded corners. So a better cross-browser way to handle it would be to use rounded-corner images at the corners. Many famous websites use this approach.
You can also find rounded image generators around the web. One such link is http://www.generateit.net/rounded-corner/
We usually use One Main Window
for the application and other windows can be used in situations like when you need popups because instead of using popup controls in XAML which are not visible we can use a Window that is visible at design time so that'll be easy to work with
on the other hand we use many pages to navigate from one screen to another like User management screen to Order Screen etc In the main Window we can use Frame
control for navigation like below
XAML
<Frame Name="mainWinFrame" NavigationUIVisibility="Hidden" ButtonBase.Click="mainWinFrame_Click">
</Frame>
C#
private void mainWinFrame_Click(object sender, RoutedEventArgs e)
{
try
{
if (e.OriginalSource is Button)
{
Button btn = (Button)e.OriginalSource;
if ((btn.CommandParameter != null) && (btn.CommandParameter.Equals("Order")))
{
mainWinFrame.Navigate(OrderPage);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
That's one way of doing it We can also use a Tab Control instead of Fram and Add pages to it using a Dictionary while adding new page check if the control already exists then only navigate otherwise add and navigate. I hope that'll help someone
There's a very simple answer: it's defensive programming. You know that the uses of std::size_t
, std::cout
, etc., could be made a little easier with using namespace std;
- I hope you don't need to be convinced that such a directive has no place in a header! Within a translation unit, however, you might be tempted...
The types, classes, etc., that are part of the std
namespace increase with each C++ revision. There are too many potential ambiguities if you relax the std::
qualifier. It is entirely reasonable to relax the qualifier for names within std
that you will be using frequently, e.g., using std::fprintf;
, or more probably, something like: using std::size_t;
- but unless these are already well-understood parts of the language (or specifically, the std
wrapping of the C library), just use the qualifier.
When you can use typedef
, combined with auto
and decltype
inferencing, there's really nothing to be gained from a readability / maintainability perspective.
Assuming your ints are 0, 375, 668,5 and 6:
{
"Id": "610",
"Name": "15",
"Description": "1.99",
"ItemModList": [
0,
375,
668,
5,
6
]
}
I suggest that you change "Id": "610" to "Id": 610 since it is a integer/long and not a string. You can read more about the JSON format and examples here http://json.org/
Execute:
ng v
or
ng --version
tell you the current angular cli version number
As for the intellij2018 version I am using the following configuration for better performance
-server
-Xms1024m
-Xmx4096m
-XX:MaxPermSize=1024m
-XX:ReservedCodeCacheSize=512m
-XX:+UseCompressedOops
-Dfile.encoding=UTF-8
-XX:+UseConcMarkSweepGC
-XX:+AggressiveOpts
-XX:+CMSClassUnloadingEnabled
-XX:+CMSIncrementalMode
-XX:+CMSIncrementalPacing
-XX:CMSIncrementalDutyCycleMin=0
-XX:-TraceClassUnloading
-XX:+TieredCompilation
-XX:SoftRefLRUPolicyMSPerMB=100
-ea
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-Djdk.http.auth.tunneling.disabledSchemes=""
-XX:+HeapDumpOnOutOfMemoryError
-XX:-OmitStackTraceInFastThrow
-Xverify:none
-XX:ErrorFile=$USER_HOME/java_error_in_idea_%p.log
-XX:HeapDumpPath=$USER_HOME/java_error_in_idea.hprof
I like polymorphism instead of manually checking for something:
use MooseX::Declare;
class Foo {
use MooseX::MultiMethods;
multi method foo (ArrayRef $arg){ say "arg is an array" }
multi method foo (HashRef $arg) { say "arg is a hash" }
multi method foo (Any $arg) { say "arg is something else" }
}
Foo->new->foo([]); # arg is an array
Foo->new->foo(40); # arg is something else
This is much more powerful than manual checking, as you can reuse your "checks" like you would any other type constraint. That means when you want to handle arrays, hashes, and even numbers less than 42, you just write a constraint for "even numbers less than 42" and add a new multimethod for that case. The "calling code" is not affected.
Your type library:
package MyApp::Types;
use MooseX::Types -declare => ['EvenNumberLessThan42'];
use MooseX::Types::Moose qw(Num);
subtype EvenNumberLessThan42, as Num, where { $_ < 42 && $_ % 2 == 0 };
Then make Foo support this (in that class definition):
class Foo {
use MyApp::Types qw(EvenNumberLessThan42);
multi method foo (EvenNumberLessThan42 $arg) { say "arg is an even number less than 42" }
}
Then Foo->new->foo(40)
prints arg is an even number less than 42
instead of arg is something else
.
Maintainable.
You are declaring a local variable, not a class variable. To set an instance variable (attribute), use
class Example(object):
def the_example(self):
self.itsProblem = "problem" # <-- remember the 'self.'
theExample = Example()
theExample.the_example()
print(theExample.itsProblem)
To set a class variable (a.k.a. static member), use
class Example(object):
def the_example(self):
Example.itsProblem = "problem"
# or, type(self).itsProblem = "problem"
# depending what you want to do when the class is derived.
If you are using visual studio 2005 then
public void sumAverageElements(int[] arr)
{
int size =arr.Length;
int sum = 0;
int average = 0;
for (int i = 0; i < size; i++)
{
sum += arr[i];
}
average = sum / size; // sum divided by total elements in array
Console.WriteLine("The Sum Of Array Elements Is : " + sum);
Console.WriteLine("The Average Of Array Elements Is : " + average);
}
Once you've done this
group p by p.SomeId into pg
you no longer have access to the range variables used in the initial from
. That is, you can no longer talk about p
or bp
, you can only talk about pg
.
Now, pg
is a group and so contains more than one product. All the products in a given pg
group have the same SomeId
(since that's what you grouped by), but I don't know if that means they all have the same BaseProductId
.
To get a base product name, you have to pick a particular product in the pg
group (As you are doing with SomeId
and CountryCode
), and then join to BaseProducts
.
var result = from p in Products
group p by p.SomeId into pg
// join *after* group
join bp in BaseProducts on pg.FirstOrDefault().BaseProductId equals bp.Id
select new ProductPriceMinMax {
SomeId = pg.FirstOrDefault().SomeId,
CountryCode = pg.FirstOrDefault().CountryCode,
MinPrice = pg.Min(m => m.Price),
MaxPrice = pg.Max(m => m.Price),
BaseProductName = bp.Name // now there is a 'bp' in scope
};
That said, this looks pretty unusual and I think you should step back and consider what you are actually trying to retrieve.
Since Java 1.7 you can use Objects.equals:
java.util.Objects.equals(oneInteger, anotherInteger);
Returns true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals method of the first argument.
$headers = apache_request_headers();
$is_ajax = (isset($headers['X-Requested-With']) && $headers['X-Requested-With'] == 'XMLHttpRequest');
VideoView videoView =(VideoView) findViewById(R.id.videoViewId);
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()+"/yourvideo");
videoView.setVideoURI(uri);
videoView.start();
Instead of using setVideoPath use setVideoUri. you can get path of your video stored in external storage by using (Environment.getExternalStorageDirectory().getAbsolutePath()+"/yourvideo")and parse it into Uri. If your video is stored in sdcard/MyVideo/video.mp4 replace "/yourvideo" in code by "/MyVideo/video.mp4"
This works fine for me :) `
For SQL Server 2000, this should tell you only the #temp tables in your session. (Adapted from my example for more modern versions of SQL Server here.) This assumes you don't name your tables with three consecutive underscores, like CREATE TABLE #foo___bar
:
SELECT
name = SUBSTRING(t.name, 1, CHARINDEX('___', t.name)-1),
t.id
FROM tempdb..sysobjects AS t
WHERE t.name LIKE '#%[_][_][_]%'
AND t.id =
OBJECT_ID('tempdb..' + SUBSTRING(t.name, 1, CHARINDEX('___', t.name)-1));
As others have said you're subtracting from the numeric values returned from methods like date.getDate()
, you need to reset those values on your date variable. I've created a method below that will do this for you. It creates a date using new Date()
which will initialize with the current date, then sets the date, month, and year according to the values passed in. For example, if you want to go back 6 days then pass in -6 like so var newdate = createDate(-6,0,0)
. If you don't want to set a value pass in a zero (or you could set default values). The method will return the new date for you (tested in Chrome and Firefox).
function createDate(days, months, years) {
var date = new Date();
date.setDate(date.getDate() + days);
date.setMonth(date.getMonth() + months);
date.setFullYear(date.getFullYear() + years);
return date;
}
I always set the time to DateTime.MinValue
. This way I do not get any NullErrorException and I can compare it to a date that I know isn't set.
My problem was that POST requests need trailing slashes '/'.
<div class="foo">Foo Bar</div>
and in your CSS file:
.foo {
background-image: url("images/foo.png");
}
To convert a DateTime
to a TimeSpan
you should choose a base date/time - e.g. midnight of January 1st, 2000, and subtract it from your DateTime
value (and add it when you want to convert back to DateTime
).
If you simply want to convert a DateTime
to a number you can use the Ticks
property.
Try using flex:
Plunker demo : https://plnkr.co/edit/nk02ojKuXD2tAqZiWvf9
/* Styles go here */
html,
body {
margin: 0;
padding: 0;
}
.container {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 100vh;
grid-gap: 0px 0px;
}
.left_bg {
background-color: #3498db;
grid-column: 1 / 1;
grid-row: 1 / 1;
z-index: 0;
display: flex;
justify-content: center;
align-items: center;
}
.right_bg {
background-color: #ecf0f1;
grid-column: 2 / 2;
grid_row: 1 / 1;
z-index: 0;
display: flex;
justify-content: center;
align-items: center;
}
.text {
font-family: Raleway;
font-size: large;
text-align: center;
}
HTML
<div class="container">
<!--everything on the page-->
<div class="left_bg">
<!--left background color of the page-->
<div class="text">
<!--left side text content-->
<p>Review my stuff</p>
</div>
</div>
<div class="right_bg">
<!--right background color of the page-->
<div class="text">
<!--right side text content-->
<p>Hire me!</p>
</div>
</div>
</div>
the htaccess solution
<filesmatch "\.(?i:doc|odf|pdf|cer|txt)$">
Header set Content-Disposition attachment
</FilesMatch>
you can read this page: https://www.techmesto.com/force-files-to-download-using-htaccess/
There are three versions: assembly, file, and product. They are used by different features and take on different default values if you don't explicit specify them.
string assemblyVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();
string assemblyVersion = Assembly.LoadFile("your assembly file").GetName().Version.ToString();
string fileVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion;
string productVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion;
If you want to import A.ipynb
in B.ipynb
write
import import_ipynb
import A
in B.ipynb
.
The import_ipynb
module I've created is installed via pip:
pip install import_ipynb
It's just one file and it strictly adheres to the official howto on the jupyter site.
PS It also supports things like from A import foo
, from A import *
etc
The onload property of the GlobalEventHandlers mixin is an event handler for the load event of a Window, XMLHttpRequest, element, etc., which fires when the resource has loaded.
So basically javascript already has onload method on window which get executed which page fully loaded including images...
You can do something:
var spinner = true;
window.onload = function() {
//whatever you like to do now, for example hide the spinner in this case
spinner = false;
};
soup = BeautifulSoup(html)
for hit in soup.findAll(attrs={'class' : 'MYCLASS'}):
hit = hit.text.strip()
print hit
This will print: THIS IS MY TEXT Try this..
Here's a nice easy way I found:
h <- hist(g, breaks = 10, density = 10,
col = "lightgray", xlab = "Accuracy", main = "Overall")
xfit <- seq(min(g), max(g), length = 40)
yfit <- dnorm(xfit, mean = mean(g), sd = sd(g))
yfit <- yfit * diff(h$mids[1:2]) * length(g)
lines(xfit, yfit, col = "black", lwd = 2)
Here's a new way of putting dots in password
<EditText
android:id="@+id/loginPassword"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="@string/pwprompt" /
add android:inputType = "textPassword"
var newTH = document.createElement('th');
newTH.setAttribute("onclick", "removeColumn(#)");
newTH.setAttribute("id", "#");
function removeColumn(#){
// remove column #
}
You say your website is in http://localhost/mywebsite
, and let's say that your image is inside a subfolder named pictures/
:
Absolute path
If you use an absolute path, /
would point to the root of the site, not the root of the document: localhost
in your case. That's why you need to specify your document's folder in order to access the pictures folder:
"/mywebsite/pictures/picture.png"
And it would be the same as:
"http://localhost/mywebsite/pictures/picture.png"
Relative path
A relative path is always relative to the root of the document, so if your html is at the same level of the directory, you'd need to start the path directly with your picture's directory name:
"pictures/picture.png"
But there are other perks with relative paths:
dot-slash (./
)
Dot (.
) points to the same directory and the slash (/
) gives access to it:
So this:
"pictures/picture.png"
Would be the same as this:
"./pictures/picture.png"
Double-dot-slash (../
)
In this case, a double dot (..
) points to the upper directory and likewise, the slash (/
) gives you access to it. So if you wanted to access a picture that is on a directory one level above of the current directory your document is, your URL would look like this:
"../picture.png"
You can play around with them as much as you want, a little example would be this:
Let's say you're on directory A
, and you want to access directory X
.
- root
|- a
|- A
|- b
|- x
|- X
Your URL would look either:
Absolute path
"/x/X/picture.png"
Or:
Relative path
"./../x/X/picture.png"
Yes, Mid
.
Dim sub_str
sub_str = Mid(source_str, 10, 5)
The first parameter is the source string, the second is the start index, and the third is the length.
@bobobobo: Note that VBScript strings are 1-based, not 0-based. Passing 0 as an argument to Mid
results in "invalid procedure call or argument Mid".
Browsers can often tell the image type by sniffing out the meta information of the image. Also, there should be a space in that header:
header('Content-type: image/png');
You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model
Post.objects.all().delete()
and to delete any Post with a future publication date
Post.objects.filter(pub_date__gt=datetime.now()).delete()
You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.
EDIT:
Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForm
s and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.
No, it is not a bad practice. It is the most easiest and efficient way.
select @myInt = COUNT(*) from myTable
You need to return the validating function. Something like:
onsubmit="return validateForm();"
Then the validating function should return false on errors. If everything is OK return true. Remember that the server has to validate as well.
Check out Google Collections' Multimap
, e.g. page 28 of this presentation.
If you can't use that library for some reason, consider using ConcurrentHashMap
instead of SynchronizedHashMap
; it has a nifty putIfAbsent(K,V)
method with which you can atomically add the element list if it's not already there. Also, consider using CopyOnWriteArrayList
for the map values if your usage patterns warrant doing so.
Be sure you have C++ Redistributable for Visual Studio 2015 RC. Try to download the last version:
https://www.microsoft.com/en-us/download/details.aspx?id=52685
Obs: Credit to parsecer
To help guard against SQL injection, I normally try to use functions wherever possible. In this case, you could do:
...
SET @TableName = '<[db].><[schema].>tblEmployees'
SET @TableID = OBJECT_ID(TableName) --won't resolve if malformed/injected.
...
SET @SQLQuery = 'SELECT * FROM ' + OBJECT_NAME(@TableID) + ' WHERE EmployeeID = @EmpID'
Have you tried setting the scroll direction of your UICollectionViewFlowLayout to horizontal?
[yourFlowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
And if you want it to page like springboard does, you'll need to enable paging on your collection view like so:
[yourCollectionView setPagingEnabled:YES];
I just installed MySQL 5.7 on Windows7. The database files are located in the following directory which is a hidden one:
C:\ProgramData\MySQL\MySQL Server 5.7\Data
The my.ini
file is located in the same root: C:\ProgramData\MySQL\MySQL Server 5.7
For some reason the responsive table in particular doesn't behave as it should. You can patch it by getting rid of display:block;
.table-responsive {
display: table;
}
I may file a bug report.
Edit:
I think this should work
destroyView : function () {
this.$el.remove();
}