Based on the answer above from Daniel, here's my take using Python3.
import numpy
def circlepoints(points,radius,center):
shape = []
slice = 2 * 3.14 / points
for i in range(points):
angle = slice * i
new_x = center[0] + radius*numpy.cos(angle)
new_y = center[1] + radius*numpy.sin(angle)
p = (new_x,new_y)
shape.append(p)
return shape
print(circlepoints(100,20,[0,0]))
This will surely work:
UPDATE table1
SET table1.price=(SELECT table2.price
FROM table2
WHERE table2.id=table1.id AND table2.item=table1.item);
I think the point is that there is no need to quit the app unless you have buggy software. Android quits the app when the user is not using it and the device needs more memory. If you have an app that needs to run a service in the background, you will likely want a way to turn the service off.
For example, Google Listen continues to play podcast when the app is not visible. But there is always the pause button to turn the podcast off when the user is done with it. If I remember correctly, Listen, even puts a shortcut in the notification bar so you can always get to the pause button quickly. Another example is an app like a twitter app for instance which constantly polls a service on the internet. These types of apps should really allow the user to choose how often to poll the server, or whether even to poll in a background thread.
If you need to have code that runs on exit, you can override onPause(), onStop(), or onDestroy() as appropriate. http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
This code worked fine for me.
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
public class SaveImageFromUrl {
public static void main(String[] args) throws Exception {
String imageUrl = "http://www.avajava.com/images/avajavalogo.jpg";
String destinationFile = "image.jpg";
saveImage(imageUrl, destinationFile);
}
public static void saveImage(String imageUrl, String destinationFile) throws IOException {
URL url = new URL(imageUrl);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(destinationFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}
}
If you don't know when data will be added to #data
, you could set an interval to update the element's scrollTop to its scrollHeight every couple of seconds. If you are controlling when data is added, just call the internal of the following function after the data has been added.
window.setInterval(function() {
var elem = document.getElementById('data');
elem.scrollTop = elem.scrollHeight;
}, 5000);
It is possible!
But what exactly is possible, let's narrow down. People often want some kind of "static virtual function" because of duplication of code needed for being able to call the same function through static call "SomeDerivedClass::myfunction()" and polymorphic call "base_class_pointer->myfunction()". "Legal" method for allowing such functionality is duplication of function definitions:
class Object
{
public:
static string getTypeInformationStatic() { return "base class";}
virtual string getTypeInformation() { return getTypeInformationStatic(); }
};
class Foo: public Object
{
public:
static string getTypeInformationStatic() { return "derived class";}
virtual string getTypeInformation() { return getTypeInformationStatic(); }
};
What if base class has a great number of static functions and derived class has to override every of them and one forgot to provide a duplicating definition for virtual function. Right, we'll get some strange error during runtime which is hard to track down. Cause duplication of code is a bad thing. The following tries to resolve this problem (and I want to tell beforehand that it is completely type-safe and doesn't contain any black magic like typeid's or dynamic_cast's :)
So, we want to provide only one definition of getTypeInformation() per derived class and it is obvious that it has to be a definition of static function because it is not possible to call "SomeDerivedClass::getTypeInformation()" if getTypeInformation() is virtual. How can we call static function of derived class through pointer to base class? It is not possible with vtable because vtable stores pointers only to virtual functions and since we decided not to use virtual functions, we cannot modify vtable for our benefit. Then, to be able to access static function for derived class through pointer to base class we have to store somehow the type of an object within its base class. One approach is to make base class templatized using "curiously recurring template pattern" but it is not appropriate here and we'll use a technique called "type erasure":
class TypeKeeper
{
public:
virtual string getTypeInformation() = 0;
};
template<class T>
class TypeKeeperImpl: public TypeKeeper
{
public:
virtual string getTypeInformation() { return T::getTypeInformationStatic(); }
};
Now we can store the type of an object within base class "Object" with a variable "keeper":
class Object
{
public:
Object(){}
boost::scoped_ptr<TypeKeeper> keeper;
//not virtual
string getTypeInformation() const
{ return keeper? keeper->getTypeInformation(): string("base class"); }
};
In a derived class keeper must be initialized during construction:
class Foo: public Object
{
public:
Foo() { keeper.reset(new TypeKeeperImpl<Foo>()); }
//note the name of the function
static string getTypeInformationStatic()
{ return "class for proving static virtual functions concept"; }
};
Let's add syntactic sugar:
template<class T>
void override_static_functions(T* t)
{ t->keeper.reset(new TypeKeeperImpl<T>()); }
#define OVERRIDE_STATIC_FUNCTIONS override_static_functions(this)
Now declarations of descendants look like:
class Foo: public Object
{
public:
Foo() { OVERRIDE_STATIC_FUNCTIONS; }
static string getTypeInformationStatic()
{ return "class for proving static virtual functions concept"; }
};
class Bar: public Foo
{
public:
Bar() { OVERRIDE_STATIC_FUNCTIONS; }
static string getTypeInformationStatic()
{ return "another class for the same reason"; }
};
usage:
Object* obj = new Foo();
cout << obj->getTypeInformation() << endl; //calls Foo::getTypeInformationStatic()
obj = new Bar();
cout << obj->getTypeInformation() << endl; //calls Bar::getTypeInformationStatic()
Foo* foo = new Bar();
cout << foo->getTypeInformation() << endl; //calls Bar::getTypeInformationStatic()
Foo::getTypeInformation(); //compile-time error
Foo::getTypeInformationStatic(); //calls Foo::getTypeInformationStatic()
Bar::getTypeInformationStatic(); //calls Bar::getTypeInformationStatic()
Advantages:
Disadvantages:
Open issues:
1) there are different names for static and virtual functions how to solve ambiguity here?
class Foo
{
public:
static void f(bool f=true) { cout << "static";}
virtual void f() { cout << "virtual";}
};
//somewhere
Foo::f(); //calls static f(), no ambiguity
ptr_to_foo->f(); //ambiguity
2) how to implicitly call OVERRIDE_STATIC_FUNCTIONS inside every constructor?
Change 'middle' to 'center'. Like so:
<img align="center" ....>
UNIX filesystems (generally) don't store creation times. Instead, there are only access time, (data) modification time, and (inode) change time.
That being said, find
has -atime
-mtime
-ctime
predicates:
$ man 1 find ... -ctime n The primary shall evaluate as true if the time of last change of file status information subtracted from the initialization time, divided by 86400 (with any remainder discarded), is n. ...
Thus find -ctime 0
finds everything for which the inode has changed (e.g. includes file creation, but also counts link count and permissions and filesize change) less than an hour ago.
You can skip the Performance counter check in the setup altogether:
setup.exe /ACTION=install /SKIPRULES=PerfMonCounterNotCorruptedCheck
First up, you seem to be mixing table variables and tables.
Either way, You can't pass in the table's name like that. You would have to use dynamic TSQL to do that.
If you just want to declare a table variable:
CREATE PROC sp_createATable
@name VARCHAR(10),
@properties VARCHAR(500)
AS
declare @tablename TABLE
(
id CHAR(10) PRIMARY KEY
);
The fact that you want to create a stored procedure to dynamically create tables might suggest your design is wrong.
I know this thread is somewhat old, but there are a lot of really hacky answers on here, so I'd like to provide something that is a lot simpler and a lot cleaner:
select {
overflow-y: auto;
}
As you can see in this fiddle, this solution provides you with flexibility if you don't know the exact number of select options you are going to have. It hides the scrollbar in the case that you don't need it without hiding possible extra option elements in the other case. Don't do all this hacky overlapping div
stuff. It just makes for unreadable markup.
Here is the one of methods to avoid duplicates into javascript array...and it supports for strings and numbers...
var unique = function(origArr) {
var newArray = [],
origLen = origArr.length,
found,
x = 0; y = 0;
for ( x = 0; x < origLen; x++ ) {
found = undefined;
for ( y = 0; y < newArray.length; y++ ) {
if ( origArr[x] === newArray[y] ) found = true;
}
if ( !found) newArray.push( origArr[x] );
}
return newArray;
}
check this fiddle..
If you're using Apline Linux, the BusyBox netcat is slightly different:
while true; do nc -l -p 8080 -e sh -c 'echo -e "HTTP/1.1 200 OK\n\n$(date)"'; done
And another way using printf
:
while true; do nc -l -p 8080 -e sh -c "printf 'HTTP/1.1 200 OK\n\n%s' \"$(date)\""; done
To answer a little more conceptually:
SelectedValuePath
defines which property (by its name) of the objects bound to the ListBox's ItemsSource
will be used as the item's SelectedValue
.
For example, if your ListBox is bound to a collection of Person
objects, each of which has Name
, Age
, and Gender
properties, SelectedValuePath=Name
will cause the value of the selected Person
's Name
property to be returned in SelectedValue
.
Note that if you override the ListBox's ControlTemplate (or apply a Style) that specifies what property should display, SelectedValuePath
cannot be used.
SelectedItem
, meanwhile, returns the entire Person
object currently selected.
(Here's a further example from MSDN, using TreeView)
Update: As @Joe pointed out, the DisplayMemberPath property is unrelated to the Selected* properties. Its proper description follows:
Note that these values are distinct from DisplayMemberPath
(which is defined on ItemsControl, not Selector), but that property has similar behavior to SelectedValuePath
: in the absence of a style/template, it identifies which property of the object bound to item should be used as its string representation.
for using git you have to be
root
if not then use sudo
for removing origin :
git remote remove origin
for adding origin :
git remote add origin http://giturl
=ARRAYFORMULA(INDIRECT("A"&MAX(IF(A:A<>"", ROW(A:A), ))))
=ARRAYFORMULA(INDIRECT(ADDRESS(1, MAX(IF(1:1<>"", COLUMN(1:1), )), 4)))
Probably the best way to learn how to structure your program is by reading other people's code, especially if it's a large program to which many people have contributed. After looking at the code of many projects, you should get an idea of what the consensus style should be.
Python, as a language, is special in that there are some strong guidelines as to how you should format your code. The first is the so-called "Zen of Python":
- Beautiful is better than ugly.
- Explicit is better than implicit.
- Simple is better than complex.
- Complex is better than complicated.
- Flat is better than nested.
- Sparse is better than dense.
- Readability counts.
- Special cases aren't special enough to break the rules.
- Although practicality beats purity.
- Errors should never pass silently.
- Unless explicitly silenced.
- In the face of ambiguity, refuse the temptation to guess.
- There should be one-- and preferably only one --obvious way to do it.
- Although that way may not be obvious at first unless you're Dutch.
- Now is better than never.
- Although never is often better than right now.
- If the implementation is hard to explain, it's a bad idea.
- If the implementation is easy to explain, it may be a good idea.
- Namespaces are one honking great idea -- let's do more of those!
On a more practical level, there is PEP8, the style guide for Python.
With those in mind, I would say that your code style doesn't really fit, particularly the nested functions. Find a way to flatten those out, either by using classes or moving them into separate modules. This will make the structure of your program much easier to understand.
simply pipeline echo with cat
For example
echo write something to file.txt | cat > file.txt
Alternative: Stream.concat()
Stream.concat(map.values().stream(), listContainer.lst.stream())
.collect(Collectors.toList()
Be aware that a value of 1 equals 100% in Excel's interpretation. If you enter 5.66 and you want to show 5.66%, then AxGryndr's hack with the formatting will work, but it is a display format only and does not represent the true numeric value. If you want to use that percentage in further calculations, these calculations will return the wrong result unless you divide by 100 at calculation time.
The consistent and less error-prone way is to enter 0.0566 and format the number with the built-in percentage format. That way, you can easily calculate 5.6% of A1 by just multiplying A1 with the value.
The good news is that you don't need to go through the rigmarole of entering 0.0566 and then formatting as percent. You can simply type
5.66%
into the cell, including the percentage symbol, and Excel will take care of the rest and store the number correctly as 0.0566 if formatted as General.
I'm successfully using the following to update options dynamically:
$control.select2('destroy').empty().select2({data: [{id: 1, text: 'new text'}]});
Firstly, you should use randrange(0,1000)
or randint(0,999)
, not randint(0,1000)
. The upper limit of randint
is inclusive.
For efficiently, randint
is simply a wrapper of randrange
which calls random
, so you should just use random
. Also, use xrange
as the argument to sample
, not range
.
You could use
[a for a in sample(xrange(1000),1000) for _ in range(10000/1000)]
to generate 10,000 numbers in the range using sample
10 times.
(Of course this won't beat NumPy.)
$ python2.7 -m timeit -s 'from random import randrange' '[randrange(1000) for _ in xrange(10000)]'
10 loops, best of 3: 26.1 msec per loop
$ python2.7 -m timeit -s 'from random import sample' '[a%1000 for a in sample(xrange(10000),10000)]'
100 loops, best of 3: 18.4 msec per loop
$ python2.7 -m timeit -s 'from random import random' '[int(1000*random()) for _ in xrange(10000)]'
100 loops, best of 3: 9.24 msec per loop
$ python2.7 -m timeit -s 'from random import sample' '[a for a in sample(xrange(1000),1000) for _ in range(10000/1000)]'
100 loops, best of 3: 3.79 msec per loop
$ python2.7 -m timeit -s 'from random import shuffle
> def samplefull(x):
> a = range(x)
> shuffle(a)
> return a' '[a for a in samplefull(1000) for _ in xrange(10000/1000)]'
100 loops, best of 3: 3.16 msec per loop
$ python2.7 -m timeit -s 'from numpy.random import randint' 'randint(1000, size=10000)'
1000 loops, best of 3: 363 usec per loop
But since you don't care about the distribution of numbers, why not just use:
range(1000)*(10000/1000)
?
You could also use
SELECT * from Results WHERE date < NOW() - INTERVAL 30 DAY;
I had this problem in an ASP.NET application, specifically a Web Forms.
I was forcing a redirect in Global.asax, but I forgot to check if the request was for resources like css, javascript, etc. I just had to add the following checks:
VB.NET
If Not Response.IsRequestBeingRedirected _
And Not Request.Url.AbsoluteUri.Contains(".WebResource") _
And Not Request.Url.AbsoluteUri.Contains(".css") _
And Not Request.Url.AbsoluteUri.Contains(".js") _
And Not Request.Url.AbsoluteUri.Contains("images/") _
And Not Request.Url.AbsoluteUri.Contains("favicon") Then
Response.Redirect("~/change-password.aspx")
End If
I was forcing logged users which hadn't change their passwords for a long time, to be redirected to the change-password.aspx page. I believe there is a better way to check this, but for now, this worked. Should I find a better solution, I edit my answer.
I was able to install xgboost for Python in Windows yesterday by following this link. But when I tried to import using Anaconda, it failed. I recognized this is due to the fact that Anaconda has a different Python distribution. I then searched again and found this great article which made it!
The trick is after installing successfully for regular Python, to have it work for Anaconda, you just need to pull up the Anaconda prompt and cd into this folder "code\xgboost\python-package", then run:
python setup.py install
And voila! The article says you need to add the path, but for me it worked directly. Good luck!
Also copied below the original contents in case the link is not available...
Once the last command completes the build is done. We can now install the Python module. What follows depends on the Python distribution you are using. For Anaconda, I will simply use the Anaconda prompt, and type the following in it (after the prompt, in my case [Anaconda3] C:\Users\IBM_ADMIN>):
[Anaconda3] C:\Users\IBM_ADMIN>cd code\xgboost\python-package
The point is to move to the python-package directory of XGBoost. Then type:
[Anaconda3] C:\Users\IBM_ADMIN\code\xgboost\python-package>python setup.py install
We are almost done. Let's launch a notebook to test XGBoost. Importing it directly causes an error. In order to avoid it we must add the path to the g++ runtime libraries to the os environment path variable with:
import os
mingw_path = 'C:\\Program Files\\mingw-w64\\x86_64-5.3.0-posix-seh-rt_v4-rev0\\mingw64\\bin'
os.environ['PATH'] = mingw_path + ';' + os.environ['PATH']
We can then import xgboost and run a small example.
import xgboost as xgb
import numpy as np
data = np.random.rand(5,10) # 5 entities, each contains 10 features
label = np.random.randint(2, size=5) # binary target
dtrain = xgb.DMatrix( data, label=label)
dtest = dtrain
param = {'bst:max_depth':2, 'bst:eta':1, 'silent':1, 'objective':'binary:logistic' }
param['nthread'] = 4
param['eval_metric'] = 'auc'
evallist = [(dtest,'eval'), (dtrain,'train')]
num_round = 10
bst = xgb.train( param, dtrain, num_round, evallist )
bst.dump_model('dump.raw.txt')
We are all set!
Use this command, (go to java < jdk < bin path in cmd prompt)
$ jarsigner -verify -verbose -certs my_application.apk
If you see "CN=Android Debug", this means the .apk was signed with the debug key generated by the Android SDK (means it is unsigned), otherwise you will find something for CN. For more details see: http://developer.android.com/guide/publishing/app-signing.html
If you wish to run one script and only one script, you can make it that users default shell.
echo "/usr/bin/uptime" >> /etc/shells
vim /etc/passwd
* username:x:uid:grp:message:homedir:/usr/bin/uptime
can have interesting effects :) ( its not secure tho, so don't trust it too much. nothing like setting your default shell to be a script that wipes your drive. ... although, .. I can imagine a scenario where that could be amazingly useful )
After looking on the accepted answer I realized that if know size of required vector then we have to use a loop to initialize every element
But I found new to do this using default_structure_element like following...
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
typedef struct subject {
string name;
int marks;
int credits;
}subject;
int main(){
subject default_subject;
default_subject.name="NONE";
default_subject.marks = 0;
default_subject.credits = 0;
vector <subject> sub(10,default_subject); // default_subject to initialize
//to check is it initialised
for(ll i=0;i<sub.size();i++) {
cout << sub[i].name << " " << sub[i].marks << " " << sub[i].credits << endl;
}
}
Then I think its good to way to initialize a vector of the struct, isn't it?
in your tsconfig you have to add: "esModuleInterop": true - it should help.
The only thing that worked for me was to change outDir
in in both angular-cli.json
AND src/tsconfig.json
.
I wanted my dist-folder outside the angular project folder. If I didn't change the setting in src/tsconfig.json
as well, Angular CLI would throw warnings whenever I build the project.
Here are the most important lines ...
// angular-cli.json
{
...
"apps": [
{
"outDir": "../dist",
...
}
],
...
}
And ...
// tsconfig.json
{
"compilerOptions": {
"outDir": "../../dist/out-tsc",
...
}
}
Just to add to the helpful and detailed answer:
If you have to check the exit code explicitly, it is better to use the arithmetic operator, (( ... ))
, this way:
run_some_command
(($? != 0)) && { printf '%s\n' "Command exited with non-zero"; exit 1; }
Or, use a case
statement:
run_some_command; ec=$? # grab the exit code into a variable so that it can
# be reused later, without the fear of being overwritten
case $ec in
0) ;;
1) printf '%s\n' "Command exited with non-zero"; exit 1;;
*) do_something_else;;
esac
Related answer about error handling in Bash:
The obvious answer would be to generate different ids, a separate id for each text box, something like
[int i=0]
<% Using Html.BeginForm()%>
<% For Each item In Model.MyRecords%>
[i++]
<%=Html.TextBox("my_date[i]")%> <br/>
<% Next%>
<% End Using%>
I don't know ASP.net so I just added some general C-like syntax code within square brackets. Translating it to actual ASP.net code shouldn't be a problem.
Then, you have to find a way to generate as many
$('#my_date[i]').datepicker();
as items in your Model.MyRecords
. Again, within square brackets is your counter, so your jQuery function would be something like:
<script type="text/javascript">
$(function() {
$('#my_date1').datepicker();
$('#my_date2').datepicker();
$('#my_date3').datepicker();
...
});
</script>
In case somebody is still looking for dynamic function call with dynamic parameters -
callFunction("aaa('hello', 'world')");
function callFunction(func) {
try
{
eval(func);
}
catch (e)
{ }
}
function aaa(a, b) {
alert(a + ' ' + b);
}
I've had a same problem with react-redux types. The simplest solution was add to tsconfig.json:
"noImplicitAny": false
{
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"isolatedModules": true,
"jsx": "react",
"lib": ["es6"],
"moduleResolution": "node",
"noEmit": true,
"strict": true,
"target": "esnext",
"noImplicitAny": false,
},
"exclude": ["node_modules", "babel.config.js", "metro.config.js", "jest.config.js"]
}
There's a very nice package called nb_dev which is designed for authoring Python packages in Jupyter Notebooks. Like nbconvert,
it can turn a notebook into a .py file, but it is more flexible and powerful because it has a lot of nice additional authoring features to help you develop tests, documentation, and register packages on PyPI. It was developed by the fast.ai folks.
It has a bit of a learning curve, but the documentation is good and it is not difficult overall.
Just wanted to add an example of when you may need to use both. I am currently writing a file handler bound to a database model in a general purpose ERP solution.
This way, I get to have multiple templates for different files and a common set of interface methods with clear distinction. The interface gives the correct analogy to the access methods rather than what would have been with a base abstract class.
Further down the line when I will make adapters for different file storage services, this implementation will allow the interface to be used elsewhere in totally different contexts.
Another good trick is to go into UTF8 mode in your editor so that you can actually see these funny characters and delete them yourself.
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array( 'prev_text' >' Previous','post_type' => 'page', 'posts_per_page' => 5, 'paged' => $paged );
$wp_query = new WP_Query($args);
while ( have_posts() ) : the_post();
//get all pages
the_ID();
the_title();
//if you want specific page of content then write
if(get_the_ID=='11')//make sure to use get_the_ID instead the_ID
{
echo get_the_ID();
the_title();
the_content();
}
endwhile;
//if you want specific page of content then write in loop
if(get_the_ID=='11')//make sure to use get_the_ID instead the_ID
{
echo get_the_ID();
the_title();
the_content();
}
I spent time finding a proper way. This may be useful for others.
Create a UDF and refer in the query -
http://www.geekzilla.co.uk/view5C09B52C-4600-4B66-9DD7-DCE840D64CBD.htm
You got a syntax wrong. Just pass in array's name. BTW - it's good idea to read some common formatting stuff too, for example in Java methods should start with lowercase letter (it's not an error it's convention)
Even u can try this
Function
CREATE FUNCTION [dbo].[fn_Split](@text varchar(8000), @delimiter varchar(20))
RETURNS @Strings TABLE
(
position int IDENTITY PRIMARY KEY,
value varchar(8000)
)
AS
BEGIN
DECLARE @index int
SET @index = -1
WHILE (LEN(@text) > 0)
BEGIN
SET @index = CHARINDEX(@delimiter , @text)
IF (@index = 0) AND (LEN(@text) > 0)
BEGIN
INSERT INTO @Strings VALUES (@text)
BREAK
END
IF (@index > 1)
BEGIN
INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))
SET @text = RIGHT(@text, (LEN(@text) - @index))
END
ELSE
SET @text = RIGHT(@text, (LEN(@text) - @index))
END
RETURN
END
Query
select * from my_table inner join (select value from fn_split('ABC,MOP',','))
as split_table on my_table.column_name like '%'+split_table.value+'%';
GCM is being replaced with FCM
Have a look at developers.android.com - Google replaced C2DM with GCM Demo Implementation / How To
1) You need to check on the server what HTTP response you are getting from the Google servers. Make sure it is a 200 OK response, so you know the message was sent. If you get another response (302, etc) then the message is not being sent successfully.
2) You also need to check that the Registration ID you are using is correct. If you provide the wrong Registration ID (as a destination for the message - specifying the app, on a specific device) then the Google servers cannot successfully send it.
3) You also need to check that your app is successfully registering with the Google servers, to receive push notifications. If the registration fails, you will not receive messages.
Here is a good question you may should have a look at it: How to add a push notification in my own android app
Also here is a good blog with a really simple how to: http://blog.serverdensity.com/android-push-notifications-tutorial/
CRTL + Backspace It works also
Easiest way to do it with javax.xml.bind.DatatypeConverter
:
String hex = "75546f7272656e745c436f6d706c657465645c6e667375635f6f73745f62795f6d757374616e675c50656e64756c756d2d392c303030204d696c65732e6d7033006d7033006d7033004472756d202620426173730050656e64756c756d00496e2053696c69636f00496e2053696c69636f2a3b2a0050656e64756c756d0050656e64756c756d496e2053696c69636f303038004472756d2026204261737350656e64756c756d496e2053696c69636f30303800392c303030204d696c6573203c4d757374616e673e50656e64756c756d496e2053696c69636f3030380050656e64756c756d50656e64756c756d496e2053696c69636f303038004d50330000";
byte[] s = DatatypeConverter.parseHexBinary(hex);
System.out.println(new String(s));
Had the same error because I forgot to send a correct header a first
header("Content-type: text/css; charset: UTF-8");
print 'body { text-align: justify; font-size: 2em; }';
The tabularx
package gives you
X
, all X
columns will grow to fill up the total width.For your example:
\usepackage{tabularx}
% ...
\begin{document}
% ...
\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF & simulation & jsp\\
\hline
\end{tabularx}
You open the variable "file" as a read only then attempt to write to it:
file = open('ValidEmails.txt','r')
Instead, use the 'w' flag.
file = open('ValidEmails.txt','w')
...
file.write(email)
It's easier to help you if you say what's wrong as well, or what fails when you run it.
But from a quick glance you've confused a few things.
The following doesn't work because of a couple of issues.
if (Directory("C:\\csharp\\error report1.xls") = "")
What you are trying to do is creating a new Directory object that should point to a file and then check if there was any errors.
What you are actually doing is trying to call a function named Directory() and then assign a string to the result. This won't work since 1/ you don't have a function named Directory(string str) and you cannot assign to the result from a function (you can only assign a value to a variable).
What you should do (for this line at least) is the following
FileInfo fi = new FileInfo("C:\\csharp\\error report1.xls");
if(!fi.Exists)
{
// Create the xl file here
}
else
{
// Open file here
}
As to why the Excel code doesn't work, you have to check the documentation for the Excel library which google should be able to provide for you.
@tennisgent's solution is great. However, I think is a little limited.
Modularity and Encapsulation in Angular goes beyond routes. Based on the way the web is moving towards component-based development, it is important to apply this in directives as well.
As you already know, in Angular we can include templates (structure) and controllers (behavior) in pages and components. AngularCSS enables the last missing piece: attaching stylesheets (presentation).
For a full solution I suggest using AngularCSS.
ng-app
in the <html>
tag. This is important when you have multiple apps running on the same pagehttps://github.com/door3/angular-css
Here are some examples:
Routes
$routeProvider
.when('/page1', {
templateUrl: 'page1/page1.html',
controller: 'page1Ctrl',
/* Now you can bind css to routes */
css: 'page1/page1.css'
})
.when('/page2', {
templateUrl: 'page2/page2.html',
controller: 'page2Ctrl',
/* You can also enable features like bust cache, persist and preload */
css: {
href: 'page2/page2.css',
bustCache: true
}
})
.when('/page3', {
templateUrl: 'page3/page3.html',
controller: 'page3Ctrl',
/* This is how you can include multiple stylesheets */
css: ['page3/page3.css','page3/page3-2.css']
})
.when('/page4', {
templateUrl: 'page4/page4.html',
controller: 'page4Ctrl',
css: [
{
href: 'page4/page4.css',
persist: true
}, {
href: 'page4/page4.mobile.css',
/* Media Query support via window.matchMedia API
* This will only add the stylesheet if the breakpoint matches */
media: 'screen and (max-width : 768px)'
}, {
href: 'page4/page4.print.css',
media: 'print'
}
]
});
Directives
myApp.directive('myDirective', function () {
return {
restrict: 'E',
templateUrl: 'my-directive/my-directive.html',
css: 'my-directive/my-directive.css'
}
});
Additionally, you can use the $css
service for edge cases:
myApp.controller('pageCtrl', function ($scope, $css) {
// Binds stylesheet(s) to scope create/destroy events (recommended over add/remove)
$css.bind({
href: 'my-page/my-page.css'
}, $scope);
// Simply add stylesheet(s)
$css.add('my-page/my-page.css');
// Simply remove stylesheet(s)
$css.remove(['my-page/my-page.css','my-page/my-page2.css']);
// Remove all stylesheets
$css.removeAll();
});
You can read more about AngularCSS here:
http://door3.com/insights/introducing-angularcss-css-demand-angularjs
I have the same problem too,and I simply close the terminal and open a new terminal and run
node server.js
again. that works for me, some time just need to wait for a few second till it work again.
But this works only on a developer machine instead of a server console..
I use shell scripts to switch me to whatever account I want to be "active". Essentially you start from a fresh start, get one account configured properly and working, then move the these files to a name with the proper prefix. From then on you can use the command "github", or "gitxyz" to switch:
# my github script
cd ~/.ssh
if [ -f git_dhoerl -a -f git_dhoerl.pub -a -f config_dhoerl ]
then
;
else
echo "Error: missing new files"
exit 1
fi
# Save a copy in /tmp, just in case
cp id_rsa /tmp
cp id_rsa.pub /tmp
cp config /tmp
echo "Saved old files in /tmp, just in case"
rm id_rsa
rm id_rsa.pub
rm config
echo "Removed current links/files"
ln git_dhoerl id_rsa
ln git_dhoerl.pub id_rsa.pub
ln config_dhoerl config
git config --global user.email "dhoerl@<company>.com"
git config --global github.user "dhoerl"
git config --global github.token "whatever_it_is"
ssh-add -D
I've had great luck with this. I also created a run script in Xcode (for you Mac users) so it would not build my project unless I had the proper setting (since its using git):
Run Script placed after Dependencies (using /bin/ksh as the shell):
if [ "$(git config --global --get user.email)" != "dhoerl@<company>.com" ]
then
exit 1
fi
EDIT: added tests for new files existence and copying old files to /tmp to address comment by @naomik below.
I am adding to this question a little interesting tip that may help you guys testing JWT Apis.
Its is very simple actually.
When you log in, in your Api (login endpoint), you will immediately receive your token, and as @mick-cullen said you will have to use the JWT on your header as:
Authorization: Bearer TOKEN_STRING
Now if you like to automate or just make your life easier, your tests you can save the token as a global that you can call on all other endpoints as:
Authorization: Bearer {{jwt_token}}
On Postman: Then make a Global variable in postman as jwt_token = TOKEN_STRING.
On your login endpoint: To make it useful, add on the beginning of the Tests Tab add:
var data = JSON.parse(responseBody);
postman.clearGlobalVariable("jwt_token");
postman.setGlobalVariable("jwt_token", data.jwt_token);
I am guessing that your api is returning the token as a json on the response as: {"jwt_token":"TOKEN_STRING"}, there may be some sort of variation.
On the first line you add the response to the data varibale. Clean your Global And assign the value.
So now you have your token on the global variable, what makes easy to use Authorization: Bearer {{jwt_token}} on all your endpoints.
Hope this tip helps.
EDIT
Something to read
About tests on Postman: testing examples
Command Line: Newman
Nice blog post: master api test automation
I had the same problem trying to make an interactive ssh session using ssh, a fork of Paramiko.
I dug around and found this article:
Updated link (last version before the link generated a 404): http://web.archive.org/web/20170912043432/http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/
To continue your example you could do
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("psql -U factory -d factory -f /tmp/data.sql")
ssh_stdin.write('password\n')
ssh_stdin.flush()
output = ssh_stdout.read()
The article goes more in depth, describing a fully interactive shell around exec_command. I found this a lot easier to use than the examples in the source.
Original link: http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/
For a bandpass filter, ws is a tuple containing the lower and upper corner frequencies. These represent the digital frequency where the filter response is 3 dB less than the passband.
wp is a tuple containing the stop band digital frequencies. They represent the location where the maximum attenuation begins.
gpass is the maximum attenutation in the passband in dB while gstop is the attentuation in the stopbands.
Say, for example, you wanted to design a filter for a sampling rate of 8000 samples/sec having corner frequencies of 300 and 3100 Hz. The Nyquist frequency is the sample rate divided by two, or in this example, 4000 Hz. The equivalent digital frequency is 1.0. The two corner frequencies are then 300/4000 and 3100/4000.
Now lets say you wanted the stopbands to be down 30 dB +/- 100 Hz from the corner frequencies. Thus, your stopbands would start at 200 and 3200 Hz resulting in the digital frequencies of 200/4000 and 3200/4000.
To create your filter, you'd call buttord as
fs = 8000.0
fso2 = fs/2
N,wn = scipy.signal.buttord(ws=[300/fso2,3100/fso2], wp=[200/fs02,3200/fs02],
gpass=0.0, gstop=30.0)
The length of the resulting filter will be dependent upon the depth of the stop bands and the steepness of the response curve which is determined by the difference between the corner frequency and stopband frequency.
Yes, it is possible. You have to do something like this:
if(isset($_POST['submit']))
{
$type_id = ($_POST['type_id'] == '' ? "null" : "'".$_POST['type_id']."'");
$sql = "INSERT INTO `table` (`type_id`) VALUES (".$type_id.")";
}
It checks if the $_POST['type_id']
variable has an empty value.
If yes, it assign NULL
as a string to it.
If not, it assign the value with ' to it for the SQL
notation
More simple in Laravel 5.7 and 5.8
{{ Request()->parameter }}
It looks like a permissions issue - not a Windows 7 issue.
Your ssh key is not authorised - Permission denied (publickey)
.
You need to create a public ssh key and ask the administrator of the Git repository to add the ssh
public key
Information on how to do this: Saving ssh key fails
As @Kimble has said, with Jackson 2, using the default formatting is very easy; simply register JodaModule
on your ObjectMapper
.
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
For custom serialization/de-serialization of DateTime
, you need to implement your own StdScalarSerializer
and StdScalarDeserializer
; it's pretty convoluted, but anyway.
For example, here's a DateTime
serializer that uses the ISODateFormat
with the UTC time zone:
public class DateTimeSerializer extends StdScalarSerializer<DateTime> {
public DateTimeSerializer() {
super(DateTime.class);
}
@Override
public void serialize(DateTime dateTime,
JsonGenerator jsonGenerator,
SerializerProvider provider) throws IOException, JsonGenerationException {
String dateTimeAsString = ISODateTimeFormat.withZoneUTC().print(dateTime);
jsonGenerator.writeString(dateTimeAsString);
}
}
And the corresponding de-serializer:
public class DateTimeDesrializer extends StdScalarDeserializer<DateTime> {
public DateTimeDesrializer() {
super(DateTime.class);
}
@Override
public DateTime deserialize(JsonParser jsonParser,
DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
try {
JsonToken currentToken = jsonParser.getCurrentToken();
if (currentToken == JsonToken.VALUE_STRING) {
String dateTimeAsString = jsonParser.getText().trim();
return ISODateTimeFormat.withZoneUTC().parseDateTime(dateTimeAsString);
}
} finally {
throw deserializationContext.mappingException(getValueClass());
}
}
Then tie these together with a module:
public class DateTimeModule extends SimpleModule {
public DateTimeModule() {
super();
addSerializer(DateTime.class, new DateTimeSerializer());
addDeserializer(DateTime.class, new DateTimeDeserializer());
}
}
Then register the module on your ObjectMapper
:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new DateTimeModule());
import io, pygame, zipfile
archive = zipfile.ZipFile('images.zip', 'r')
# read bytes from archive
img_data = archive.read('img_01.png')
# create a pygame-compatible file-like object from the bytes
bytes_io = io.BytesIO(img_data)
img = pygame.image.load(bytes_io)
I was trying to figure this out for myself just now and thought this might be useful for anyone who comes across this question in the future.
Object doesn't support this property or method.
Think of it like if anything after the dot is called on an object. It's like a chain.
An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot .
you get intelli-sense (that white dropdown) trying to help you pick the correct action.
(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)
Type this much anywhere in your code area
Dim a As Worksheets
a.
you get help from VBE, it's a little dropdown called Intelli-sense
It lists all available actions that particular object exposes to any user. You can't see the .Selection
member of the Worksheets()
class. That's what the error tells you exactly.
Object doesn't support this property or method.
If you look at the example on MSDN
Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count
It activates
the sheet first then calls the Selection...
it's not connected together because Selection
is not a member of Worksheets()
class. Simply, you can't prefix the Selection
What about
Sub DisplayColumnCount()
Dim iAreaCount As Integer
Dim i As Integer
Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count
If iAreaCount <= 1 Then
MsgBox "The selection contains " & Selection.Columns.Count & " columns."
Else
For i = 1 To iAreaCount
MsgBox "Area " & i & " of the selection contains " & _
Selection.Areas(i).Columns.Count & " columns."
Next i
End If
End Sub
from HERE
You can use (this)
to reference the object that fired the function.
'this'
is a DOM element when you are inside of a callback function (in the context of jQuery), for example, being called by the click, each, bind, etc. methods.
Here is where you can learn more: http://remysharp.com/2007/04/12/jquerys-this-demystified/
Well, we're using Amazon Web Services and so we are looking to use scripts and programs to get through this problem. So I have been on the hunt for a command line tool. So first I tried the trick of running
c:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i
but because I'm running a cloud based Windows Server 2012 it complained
This option is not supported on this version of the operating system. Administrators should instead install/uninstall ASP.NET 4.5 with IIS8 using the "Turn Windows Features On/Off" dialog, the Server Manager management tool, or the dism.exe command line tool. For more details please see http://go.microsoft.com/fwlink/?LinkID=216771.
and I Googled and found the official Microsoft Support Page KB2736284. So there is a command line tool dism.exe
. So I tried the following
dism /online /enable-feature /featurename:IIS-ASPNET45
but it complained and gave a list of featurenames to try, so I tried them one by one and I tested my WebAPI webpage after each and it worked after the bottom one in the list.
dism /online /enable-feature /featurename:IIS-ApplicationDevelopment
dism /online /enable-feature /featurename:IIS-ISAPIFilter
dism /online /enable-feature /featurename:IIS-ISAPIExtensions
dism /online /enable-feature /featurename:IIS-NetFxExtensibility45
And so now I can browse to my WebAPI site and see the API information. That should help a few people. [However, I am not out of the woods totally myself yet and I cannot reach the website from outside the box. Still working on it.]
Also, I did some earlier steps following other people responses. I can confirm that the following Feature Delegation needs to be change (though I'd like to find a command line tool for these).
In Feature delegation
Change
'Handler Mappings' from Read Only to Read/Write
Change
'Modules' from Read Only to Read/Write
Change
'SSL Settings' from Read Only to Read/Write
It's just PHP, not HTML.
It parses all HTML fields with [] into an array.
So you can have
<input type="checkbox" name="food[]" value="apple" />
<input type="checkbox" name="food[]" value="pear" />
and when submitted, PHP will make $_POST['food'] an array, and you can access its elements like so:
echo $_POST['food'][0]; // would output first checkbox selected
or to see all values selected:
foreach( $_POST['food'] as $value ) {
print $value;
}
Anyhow, don't think there is a specific name for it
You could add a static method in your enum that accepts an int
as a parameter and returns a PcapLinkType
.
public static PcapLinkType of(int linkType) {
switch (linkType) {
case -1: return DLT_UNKNOWN
case 0: return DLT_NULL;
//ETC....
default: return null;
}
}
- What does the ENABLE_BITCODE actually do, will it be a non-optional requirement in the future?
I'm not sure at what level you are looking for an answer at, so let's take a little trip. Some of this you may already know.
When you build your project, Xcode invokes clang
for Objective-C targets and swift
/swiftc
for Swift targets. Both of these compilers compile the app to an intermediate representation (IR), one of these IRs is bitcode. From this IR, a program called LLVM takes over and creates the binaries needed for x86 32 and 64 bit modes (for the simulator) and arm6/arm7/arm7s/arm64 (for the device). Normally, all of these different binaries are lumped together in a single file called a fat binary.
The ENABLE_BITCODE option cuts out this final step. It creates a version of the app with an IR bitcode binary. This has a number of nice features, but one giant drawback: it can't run anywhere. In order to get an app with a bitcode binary to run, the bitcode needs to be recompiled (maybe assembled or transcoded… I'm not sure of the correct verb) into an x86 or ARM binary.
When a bitcode app is submitted to the App Store, Apple will do this final step and create the finished binaries.
Right now, bitcode apps are optional, but history has shown Apple turns optional things into requirements (like 64 bit support). This usually takes a few years, so third party developers (like Parse) have time to update.
- can I use the above method without any negative impact and without compromising a future appstore submission?
Yes, you can turn off ENABLE_BITCODE and everything will work just like before. Until Apple makes bitcode apps a requirement for the App Store, you will be fine.
- Are there any performance impacts if I enable / disable it?
There will never be negative performance impacts for enabling it, but internal distribution of an app for testing may get more complicated.
As for positive impacts… well that's complicated.
For distribution in the App Store, Apple will create separate versions of your app for each machine architecture (arm6/arm7/arm7s/arm64) instead of one app with a fat binary. This means the app installed on iOS devices will be smaller.
In addition, when bitcode is recompiled (maybe assembled or transcoded… again, I'm not sure of the correct verb), it is optimized. LLVM is always working on creating new a better optimizations. In theory, the App Store could recreate the separate version of the app in the App Store with each new release of LLVM, so your app could be re-optimized with the latest LLVM technology.
Here is a VBA approach:
Sub change()
toText Sheets(1).Range("A1:F20")
End Sub
Sub toText(target As Range)
Dim cell As Range
For Each cell In target
cell.Value = cell.Text
cell.NumberFormat = "@"
Next cell
End Sub
If you are looking for a solution without programming, the Question should be moved to SuperUser.
You can use svn+ssh:, and then it's based on access control to the repository at the given location.
This is how I host a project group repository at my uni, where I can't set up anything else. Just having a directory that the group owns, and running svn-admin (or whatever it was) in there means that I didn't need to do any configuration.
Environment.NewLine should be used as Dan Rigby said but there is one problem with the String.Empty. It will remain always empty no matter if it is read before or after it reads. I had a problem in my project yesterday with that. I removed it and it worked the way it was supposed to. It's better to declare the variable and then call it when it's needed. String.Empty will always keep it empty unless the variable needs to be initialized which only then should you use String.Empty. Thought I would throw this tid-bit out for everyone as I've experienced it.
You don't need to wrap it in a list with [..]
, just provide the subselection of the columns index:
df.drop(df.columns[[1, 69]], axis=1, inplace=True)
as the index object is already regarded as list-like.
If none of the above answers work, you can run the test in IDE, get the class path and use it in your command. Ex: If you are using Intellij IDEA, you can find it at the top of the console(screenshot below).
Clicking on the highlighted part expands and displays the complete class path.
you need to remove the references to jars inside the folder: JetBrains\IntelliJ IDEA Community Edition VERSION
java -cp "path_copied" org.testng.TestNG testng.xml
If the project is a Maven project, you can add maven surefire plugin and provide testng suite XML file path, navigate to the project directory and run the command: mvn clean install test
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>config/testrun_config.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
I think this would work
moment().weekday(); //if today is thursday it will return 4
If you can change the order of the elements, floating will work.
section {_x000D_
position: relative;_x000D_
width: 50%;_x000D_
border: 1px solid;_x000D_
}_x000D_
h1 {_x000D_
display: inline;_x000D_
}_x000D_
div {_x000D_
float: right;_x000D_
}
_x000D_
<section>_x000D_
<div>_x000D_
<button>button</button>_x000D_
</div>_x000D_
_x000D_
<h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>_x000D_
</section>
_x000D_
?By placing the div
before the h1
and floating it to the right
, you get the desired effect.
In your code you are assigning a native method to a property of custom object.
When you call support.animationFrame(function () {})
, it is executed in the context of current object (ie support). For the native requestAnimationFrame function to work properly, it must be executed in the context of window
.
So the correct usage here is support.animationFrame.call(window, function() {});
.
The same happens with alert too:
var myObj = {
myAlert : alert //copying native alert to an object
};
myObj.myAlert('this is an alert'); //is illegal
myObj.myAlert.call(window, 'this is an alert'); // executing in context of window
Another option is to use Function.prototype.bind() which is part of ES5 standard and available in all modern browsers.
var _raf = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
var support = {
animationFrame: _raf ? _raf.bind(window) : null
};
I thought I would add to this question as it is the top google search result.
As has been noted in the comments, in EF Core there is no support for using annotations (Key attribute) and it must be done with fluent.
As I was working on a large migration from EF6 to EF Core this was unsavoury and so I tried to hack it by using Reflection to look for the Key attribute and then apply it during OnModelCreating
// get all composite keys (entity decorated by more than 1 [Key] attribute
foreach (var entity in modelBuilder.Model.GetEntityTypes()
.Where(t =>
t.ClrType.GetProperties()
.Count(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(KeyAttribute))) > 1))
{
// get the keys in the appropriate order
var orderedKeys = entity.ClrType
.GetProperties()
.Where(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(KeyAttribute)))
.OrderBy(p =>
p.CustomAttributes.Single(x => x.AttributeType == typeof(ColumnAttribute))?
.NamedArguments?.Single(y => y.MemberName == nameof(ColumnAttribute.Order))
.TypedValue.Value ?? 0)
.Select(x => x.Name)
.ToArray();
// apply the keys to the model builder
modelBuilder.Entity(entity.ClrType).HasKey(orderedKeys);
}
I haven't fully tested this in all situations, but it works in my basic tests. Hope this helps someone
We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.
Check your linker flags:
Target > Build Settings > Other Linker Flags
You should see -lApptentiveConnect
listed as a linker flag:
... -ObjC -lApptentiveConnect ...
You should also see our required Frameworks listed:
UIKit
-ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit
Visual Studio for Windows Apps is meant to be used to build Windows Store Apps using HTML & Javascript or WinRT and XAML. These can also run on the Windows tablet that run Windows RT.
Visual Studio for Windows Desktop is meant to build applications using Windows Forms or Windows Presentation Foundation, these can run on Windows 8.1 on a normal desktop or on a tablet device like the Surface Pro in desktop mode (like a classic windows application).
Make sure you have the correct database selected. You may have the master database selected if you are trying to run it in a new query window.
You can try the regex here to filter out the columns starting with "foo"
df.filter(regex='^foo*')
If you need to have the string foo in your column then
df.filter(regex='foo*')
would be appropriate.
For the next step, you can use
df[df.filter(regex='^foo*').values==1]
to filter out the rows where one of the values of 'foo*' column is 1.
One obvious and straightforward possibility is to use "if-else conditions". In that example
x <- c(1, 2, 4)
y <- c(1, 4, 5)
w <- ifelse(x <= 1, "good", ifelse((x >= 3) & (x <= 5), "bad", "fair"))
data.frame(x, y, w)
** For the additional question in the edit** Is that what you expect ?
> d1 <- c("e", "c", "a")
> d2 <- c("e", "a", "b")
>
> w <- ifelse((d1 == "e") & (d2 == "e"), 1,
+ ifelse((d1=="a") & (d2 == "b"), 2,
+ ifelse((d1 == "e"), 3, 99)))
>
> data.frame(d1, d2, w)
d1 d2 w
1 e e 1
2 c a 99
3 a b 2
If you do not feel comfortable with the ifelse
function, you can also work with the if
and else
statements for such applications.
So lets say you have Activity AB that controls Frag A and Fragment B. Inside Fragment A you need an interface that Activity AB can implement. In the sample android code, they have:
private Callbacks mCallbacks = sDummyCallbacks;
/*A callback interface that all activities containing this fragment must implement. This mechanism allows activities to be notified of item selections. */
public interface Callbacks {
/*Callback for when an item has been selected. */
public void onItemSelected(String id);
}
/*A dummy implementation of the {@link Callbacks} interface that does nothing. Used only when this fragment is not attached to an activity. */
private static Callbacks sDummyCallbacks = new Callbacks() {
@Override
public void onItemSelected(String id) {
}
};
The Callback interface is put inside one of your Fragments (let’s say Fragment A). I think the purpose of this Callbacks interface is like a nested class inside Frag A which any Activity can implement. So if Fragment A was a TV, the CallBacks is the TV Remote (interface) that allows Fragment A to be used by Activity AB. I may be wrong about the detail because I'm a noob but I did get my program to work perfectly on all screen sizes and this is what I used.
So inside Fragment A, we have: (I took this from Android’s Sample programs)
@Override
public void onListItemClick(ListView listView, View view, int position, long id) {
super.onListItemClick(listView, view, position, id);
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mCallbacks.onItemSelected(DummyContent.ITEMS.get(position).id);
//mCallbacks.onItemSelected( PUT YOUR SHIT HERE. int, String, etc.);
//mCallbacks.onItemSelected (Object);
}
And inside Activity AB we override the onItemSelected method:
public class AB extends FragmentActivity implements ItemListFragment.Callbacks {
//...
@Override
//public void onItemSelected (CATCH YOUR SHIT HERE) {
//public void onItemSelected (Object obj) {
public void onItemSelected(String id) {
//Pass Data to Fragment B. For example:
Bundle arguments = new Bundle();
arguments.putString(“FragmentB_package”, id);
FragmentB fragment = new FragmentB();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction().replace(R.id.item_detail_container, fragment).commit();
}
So inside Activity AB, you basically throwing everything into a Bundle and passing it to B. If u are not sure how to use a Bundle, look the class up.
I am basically going by the sample code that Android provided. The one with the DummyContent stuff. When you make a new Android Application Package, it's the one titled MasterDetailFlow.
Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "]
with array("title" => "Welcome ")
A space may only be encoded to "+" in the "application/x-www-form-urlencoded" content-type key-value pairs query part of an URL. In my opinion, this is a MAY, not a MUST. In the rest of URLs, it is encoded as %20.
In my opinion, it's better to always encode spaces as %20, not as "+", even in the query part of an URL, because it is the HTML specification (RFC-1866) that specified that space characters should be encoded as "+" in "application/x-www-form-urlencoded" content-type key-value pairs (see paragraph 8.2.1. subparagraph 1.)
This way of encoding form data is also given in later HTML specifications. For example, look for relevant paragraphs about application/x-www-form-urlencoded in HTML 4.01 Specification, and so on.
Here is a sample string in URL where the HTML specification allows encoding spaces as pluses: "http://example.com/over/there?name=foo+bar". So, only after "?", spaces can be replaced by pluses. In other cases, spaces should be encoded to %20. But since it's hard to correctly determine the context, it's the best practice to never encode spaces as "+".
I would recommend to percent-encode all character except "unreserved" defined in RFC-3986, p.2.3
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
The implementation depends on the programming language that you chose.
If your URL contains national characters, first encode them to UTF-8 and then percent-encode the result.
You could try a global table:
create table ##global_var
(var1 int
,var2 int)
USE "DB_1"
GO
SELECT * FROM "TABLE" WHERE "COL_!" = (select var1 from ##global_var)
AND "COL_2" = @GLOBAL_VAR_2
USE "DB_2"
GO
SELECT * FROM "TABLE" WHERE "COL_!" = (select var2 from ##global_var)
Since we're all guessing, I might as well give mine: I've always thought it stood for Python. That may sound pretty stupid -- what, P for Python?! -- but in my defense, I vaguely remembered this thread [emphasis mine]:
Subject: Claiming (?P...) regex syntax extensions
From: Guido van Rossum ([email protected])
Date: Dec 10, 1997 3:36:19 pm
I have an unusual request for the Perl developers (those that develop the Perl language). I hope this (perl5-porters) is the right list. I am cc'ing the Python string-sig because it is the origin of most of the work I'm discussing here.
You are probably aware of Python. I am Python's creator; I am planning to release a next "major" version, Python 1.5, by the end of this year. I hope that Python and Perl can co-exist in years to come; cross-pollination can be good for both languages. (I believe Larry had a good look at Python when he added objects to Perl 5; O'Reilly publishes books about both languages.)
As you may know, Python 1.5 adds a new regular expression module that more closely matches Perl's syntax. We've tried to be as close to the Perl syntax as possible within Python's syntax. However, the regex syntax has some Python-specific extensions, which all begin with (?P . Currently there are two of them:
(?P<foo>...)
Similar to regular grouping parentheses, but the text
matched by the group is accessible after the match has been performed, via the symbolic group name "foo".
(?P=foo)
Matches the same string as that matched by the group named "foo". Equivalent to \1, \2, etc. except that the group is referred
to by name, not number.I hope that this Python-specific extension won't conflict with any future Perl extensions to the Perl regex syntax. If you have plans to use (?P, please let us know as soon as possible so we can resolve the conflict. Otherwise, it would be nice if the (?P syntax could be permanently reserved for Python-specific syntax extensions. (Is there some kind of registry of extensions?)
to which Larry Wall replied:
[...] There's no registry as of now--yours is the first request from outside perl5-porters, so it's a pretty low-bandwidth activity. (Sorry it was even lower last week--I was off in New York at Internet World.)
Anyway, as far as I'm concerned, you may certainly have 'P' with my blessing. (Obviously Perl doesn't need the 'P' at this point. :-) [...]
So I don't know what the original choice of P was motivated by -- pattern? placeholder? penguins? -- but you can understand why I've always associated it with Python. Which considering that (1) I don't like regular expressions and avoid them wherever possible, and (2) this thread happened fifteen years ago, is kind of odd.
I am new to Scala, but how about this to avoid throwing exceptions and repeating methods:
object awhile {
def apply(condition: () => Boolean, action: () => breakwhen): Unit = {
while (condition()) {
action() match {
case breakwhen(true) => return ;
case _ => { };
}
}
}
case class breakwhen(break:Boolean);
use it like this:
var i = 0
awhile(() => i < 20, () => {
i = i + 1
breakwhen(i == 5)
});
println(i)
if you don’t want to break:
awhile(() => i < 20, () => {
i = i + 1
breakwhen(false)
});
[tableview scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
This will take your tableview to the first row.
Also verify if breakpoints on other lines DO work, it may be a bug in the debugger. I have had a problem with the Eclipse debugger where putting a breakpoint on a boolean assignment whose code was on the next line didn't work I reported this here, but putting it on the previous or next line did.
I started to save this as a function, and call it as needed for whatever reactions require it:
function Remove(){
while(scene.children.length > 0){
scene.remove(scene.children[0]);
}
}
Now you can call the Remove(); function where appropriate.
Hi our sturucture is like Application, system, user_guide
create a folder name assets just near all the folders and then inside this assets folder create css and javascript and images folder put all your css js insiide the folders
now go to header.php and call the css just like this.
<link rel="stylesheet" href="<?php echo base_url();?>assets/css/touchTouch.css">
<link rel="stylesheet" href="<?php echo base_url();?>assets/css/style.css">
<link rel="stylesheet" href="<?php echo base_url();?>assets/css/camera.css">
Use empty()
. It checks for both empty strings and null.
if (!empty($_POST['user'])) {
// do stuff
}
From the manual:
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
Type-safe means that programmatically, the type of data for a variable, return value, or argument must fit within a certain criteria.
In practice, this means that 7 (an integer type) is different from "7" (a quoted character of string type).
PHP, Javascript and other dynamic scripting languages are usually weakly-typed, in that they will convert a (string) "7" to an (integer) 7 if you try to add "7" + 3, although sometimes you have to do this explicitly (and Javascript uses the "+" character for concatenation).
C/C++/Java will not understand that, or will concatenate the result into "73" instead. Type-safety prevents these types of bugs in code by making the type requirement explicit.
Type-safety is very useful. The solution to the above "7" + 3 would be to type cast (int) "7" + 3 (equals 10).
To use a MySQL AUTO_INCREMENT
column, you are supposed to use an IDENTITY
strategy:
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
Which is what you'd get when using AUTO
with MySQL:
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
Which is actually equivalent to
@Id @GeneratedValue
private Long id;
In other words, your mapping should work. But Hibernate should omit the id
column in the SQL insert statement, and it is not. There must be a kind of mismatch somewhere.
Did you specify a MySQL dialect in your Hibernate configuration (probably MySQL5InnoDBDialect
or MySQL5Dialect
depending on the engine you're using)?
Also, who created the table? Can you show the corresponding DDL?
Follow-up: I can't reproduce your problem. Using the code of your entity and your DDL, Hibernate generates the following (expected) SQL with MySQL:
insert
into
Operator
(active, password, username)
values
(?, ?, ?)
Note that the id
column is absent from the above statement, as expected.
To sum up, your code, the table definition and the dialect are correct and coherent, it should work. If it doesn't for you, maybe something is out of sync (do a clean build, double check the build directory, etc) or something else is just wrong (check the logs for anything suspicious).
Regarding the dialect, the only difference between MySQL5Dialect
or MySQL5InnoDBDialect
is that the later adds ENGINE=InnoDB
to the table objects when generating the DDL. Using one or the other doesn't change the generated SQL.
Escape sequences like "\n" work fine ! even with text area! I passed a java string with the "\n" to a html textarea and it worked fine as it works on consoles for java!
I am using Laravel 5.4 and unfortunately although the accepted answer seems fine, for preflighted requests (like PUT
and DELETE
) which will be preceded by an OPTIONS
request, specifying the middleware in the $routeMiddleware
array (and using that in the routes definition file) will not work unless you define a route handler for OPTIONS
as well. This is because without an OPTIONS
route Laravel will internally respond to that method without the CORS headers.
So in short either define the middleware in the $middleware
array which runs globally for all requests or if you're doing it in $middlewareGroups
or $routeMiddleware
then also define a route handler for OPTIONS
. This can be done like this:
Route::match(['options', 'put'], '/route', function () {
// This will work with the middleware shown in the accepted answer
})->middleware('cors');
I also wrote a middleware for the same purpose which looks similar but is larger in size as it tries to be more configurable and handles a bunch of conditions as well:
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
private static $allowedOriginsWhitelist = [
'http://localhost:8000'
];
// All the headers must be a string
private static $allowedOrigin = '*';
private static $allowedMethods = 'OPTIONS, GET, POST, PUT, PATCH, DELETE';
private static $allowCredentials = 'true';
private static $allowedHeaders = '';
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (! $this->isCorsRequest($request))
{
return $next($request);
}
static::$allowedOrigin = $this->resolveAllowedOrigin($request);
static::$allowedHeaders = $this->resolveAllowedHeaders($request);
$headers = [
'Access-Control-Allow-Origin' => static::$allowedOrigin,
'Access-Control-Allow-Methods' => static::$allowedMethods,
'Access-Control-Allow-Headers' => static::$allowedHeaders,
'Access-Control-Allow-Credentials' => static::$allowCredentials,
];
// For preflighted requests
if ($request->getMethod() === 'OPTIONS')
{
return response('', 200)->withHeaders($headers);
}
$response = $next($request)->withHeaders($headers);
return $response;
}
/**
* Incoming request is a CORS request if the Origin
* header is set and Origin !== Host
*
* @param \Illuminate\Http\Request $request
*/
private function isCorsRequest($request)
{
$requestHasOrigin = $request->headers->has('Origin');
if ($requestHasOrigin)
{
$origin = $request->headers->get('Origin');
$host = $request->getSchemeAndHttpHost();
if ($origin !== $host)
{
return true;
}
}
return false;
}
/**
* Dynamic resolution of allowed origin since we can't
* pass multiple domains to the header. The appropriate
* domain is set in the Access-Control-Allow-Origin header
* only if it is present in the whitelist.
*
* @param \Illuminate\Http\Request $request
*/
private function resolveAllowedOrigin($request)
{
$allowedOrigin = static::$allowedOrigin;
// If origin is in our $allowedOriginsWhitelist
// then we send that in Access-Control-Allow-Origin
$origin = $request->headers->get('Origin');
if (in_array($origin, static::$allowedOriginsWhitelist))
{
$allowedOrigin = $origin;
}
return $allowedOrigin;
}
/**
* Take the incoming client request headers
* and return. Will be used to pass in Access-Control-Allow-Headers
*
* @param \Illuminate\Http\Request $request
*/
private function resolveAllowedHeaders($request)
{
$allowedHeaders = $request->headers->get('Access-Control-Request-Headers');
return $allowedHeaders;
}
}
Also written a blog post on this.
You just need to a add the path of your PHP
file. In case you are using wamp
or have not installed it on the C drive.
The CSS properties "column-count", "column-gap", and "column-span" can do this in a way that keeps all the columns of the pseudo-table inside the same wrapper (HTML stays nice and neat).
The only caveats are that you can only define 1 column or all columns, and column-span doesn't yet work in Firefox, so some additional CSS is necessary to ensure it will displays correctly. https://www.w3schools.com/css/css3_multiple_columns.asp
.split-me {_x000D_
-webkit-column-count: 3;_x000D_
-webkit-column-gap: 0;_x000D_
-moz-column-count: 3;_x000D_
-moz-column-gap: 0;_x000D_
column-count: 3;_x000D_
column-gap: 0;_x000D_
}_x000D_
_x000D_
.cols {_x000D_
/* column-span is 1 by default */_x000D_
column-span: 1;_x000D_
}_x000D_
_x000D_
div.three-span {_x000D_
column-span: all !important;_x000D_
}_x000D_
_x000D_
/* alternate style for column-span in Firefox */_x000D_
@-moz-document url-prefix(){_x000D_
.three-span {_x000D_
position: absolute;_x000D_
left: 8px;_x000D_
right: 8px;_x000D_
top: auto;_x000D_
width: auto;_x000D_
}_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
<p>The column width stays fully dynamic, just like flex-box, evenly scaling on resize.</p>_x000D_
_x000D_
<div class='split-me'>_x000D_
<div class='col-1 cols'>Text inside Column 1 div.</div>_x000D_
<div class='col-2 cols'>Text inside Column 2 div.</div>_x000D_
<div class='col-3 cols'>Text inside Column 3 div.</div>_x000D_
<div class='three-span'>Text div spanning 3 columns.</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
_x000D_
<style>_x000D_
/* Non-Essential Visual Styles */_x000D_
_x000D_
html * { font-size: 12pt; font-family: Arial; text-align: center; }_x000D_
.split-me>* { padding: 5px; } _x000D_
.cols { border: 2px dashed black; border-left: none; }_x000D_
.col-1 { background-color: #ddffff; border-left: 2px dashed black; }_x000D_
.col-2 { background-color: #ffddff; }_x000D_
.col-3 { background-color: #ffffdd; }_x000D_
.three-span {_x000D_
border: 2px dashed black; border-top: none;_x000D_
text-align: center; background-color: #ddffdd;_x000D_
}_x000D_
</style>
_x000D_
(Decode a Base64 string to Uint8Array or ArrayBuffer with Unicode support)
If it is not defined in the web service or application or server (apache or IIS) that is hosting the web service consumable then you could create infinite connections until failure
Here is a quick example:
public class One {
/**
* @param args
*/
public static void main(String[] args) {
double a = 4.56777;
System.out.println( new Float( Math.round(a)) );
}
}
the result and output will be: 5.0
the closest upper bound Float to the starting value of double a = 4.56777
in this case the use of round is recommended since it takes in double
values and provides whole long
values
Regards
So, my case was the following. I didn't use proxy for the client-server interaction, I used ChannelFactory (thus all the advice to upgrade to service reference was meaningless to me).
The service was hosted in IIS and for some reason it had wrong references in the bin folder there. The project recompilation simply didn't lead to new dlls in that folder.
So I just deleted all the stuff from there and added reference to the service in the same solution, then recompiled and now everything works.
suppose you're posting a html form with this:
<input type="text" name="username">
If using raw cgi:
import cgi
form = cgi.FieldStorage()
print form["username"]
If using Django, Pylons, Flask or Pyramid:
print request.GET['username'] # for GET form method
print request.POST['username'] # for POST form method
Using Turbogears, Cherrypy:
from cherrypy import request
print request.params['username']
form = web.input()
print form.username
print request.form['username']
If using Cherrypy or Turbogears, you can also define your handler function taking a parameter directly:
def index(self, username):
print username
class SomeHandler(webapp2.RequestHandler):
def post(self):
name = self.request.get('username') # this will get the value from the field named username
self.response.write(name) # this will write on the document
So you really will have to choose one of those frameworks.
In my case the error was caused by cloud function invoker limit access. Please add allUsers to cloud function invoker. Please catch link. Please refer to article for more info
Select Text and selected value on dropdown/select change event in jQuery
$("#yourdropdownid").change(function() {
console.log($("option:selected", this).text()); //text
console.log($(this).val()); //value
})
Anaconda does not use the PYTHONPATH
. One should however note that if the PYTHONPATH
is set it could be used to load a library that is not in the anaconda environment. That is why before activating an environment it might be good to do a
unset PYTHONPATH
For instance this PYTHONPATH points to an incorrect pandas lib:
export PYTHONPATH=/home/john/share/usr/anaconda/lib/python
source activate anaconda-2.7
python
>>>> import pandas as pd
/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/__init__.py", line 6, in <module>
from . import hashtable, tslib, lib
ImportError: /home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
unsetting the PYTHONPATH
prevents the wrong pandas lib from being loaded:
unset PYTHONPATH
source activate anaconda-2.7
python
>>>> import pandas as pd
>>>>
Note that :
typeof $(this)
is JQuery object.
and
typeof $(this)[0]
is HTMLElement object
then :
if you want to apply .val()
on HTMLElement , you can add this extension .
HTMLElement.prototype.val=function(v){
if(typeof v!=='undefined'){this.value=v;return this;}
else{return this.value}
}
Then :
document.getElementById('myDiv').val() ==== $('#myDiv').val()
And
document.getElementById('myDiv').val('newVal') ==== $('#myDiv').val('newVal')
?????
INVERSE :Conversely? if you want to add value property to jQuery object , follow those steps :
Download the full source code (not minified) i.e: example http://code.jquery.com/jquery-1.11.1.js .
Insert Line after L96 , add this code value:""
to init this new prop
Search on jQuery.fn.init
, it will be almost Line 2747
value
prop : (Before return statment add this.value=jQuery(selector).val()
)
It seems nobody has mentioned how to do this in pure JS using the X-CSRFToken
header and {{ csrf_token }}
, so here's a simple solution where you don't need to search through the cookies or the DOM:
var xhttp = new XMLHttpRequest();
xhttp.open("POST", url, true);
xhttp.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
xhttp.send();
After you commit your object into the db the object receives a value in its ID field.
So:
myObject.Field1 = "value";
// Db is the datacontext
db.MyObjects.InsertOnSubmit(myObject);
db.SubmitChanges();
// You can retrieve the id from the object
int id = myObject.ID;
Just type path as follows instead of {Path.To.The.}: res:///{Path.To.The.}YourEdmxFileName.csdl|res:///{Path.To.The.}YourEdmxFileName.ssdl|res://*/{Path.To.The.}YourEdmxFileName.msl
const __checkIfElementExists__ = __itemFromArray__ => __itemFromArray__.*sameKey* === __outsideObject__.*samekey*;
if (cartArray.some(checkIfElementExists)) {
console.log('already exists');
} else {
alert('does not exists here')
If you're just looking to convert a given number of seconds into HH:MI:SS format, this should do it
SELECT
TO_CHAR(TRUNC(x/3600),'FM9900') || ':' ||
TO_CHAR(TRUNC(MOD(x,3600)/60),'FM00') || ':' ||
TO_CHAR(MOD(x,60),'FM00')
FROM DUAL
where x
is the number of seconds.
You can only close windows/tabs that you create yourself. That is, you cannot programmatically close a window/tab that the user creates.
For example, if you create a window with window.open()
you can close it with window.close()
.
After establising the connection and executing the query try this:
ResultSet resultSet;
int columnCount = resultSet.getMetaData().getColumnCount();
System.out.println("column count : "+columnCount);
This is an old post, but I though I should put a graphical answer here as the question is about viewing the SharedPreferences.xml
using Android Studio. So here it goes.
Go to the Tools -> Android Device Monitor. Open the device monitor by clicking it.
Then you need to select the File Explorer tab in the device monitor. Find the data folder and find another data folder inside it. It will contain a folder having the name of your application package and there will be the desired SharedPreferences.xml
.
Select the SharedPreferences.xml
file and then pull and save the file in your computer using the button marked at the top-right corner of the image above.
I've used a device emulator.
Let's do a test with 2 examples:
<?php
$memory = (int)ini_get("memory_limit"); // Display your current value in php.ini (for example: 64M)
echo "original memory: ".$memory."<br>";
ini_set('memory_limit','128M'); // Try to override the memory limit for this script
echo "new memory:".$memory;
}
// Will display:
// original memory: 64
// new memory: 64
?>
The above example doesn't work for overriding the memory_limit value. But This will work:
<?php
$memory = (int)ini_get("memory_limit"); // get the current value
ini_set('memory_limit','128'); // override the value
echo "original memory: ".$memory."<br>"; // echo the original value
$new_memory = (int)ini_get("memory_limit"); // get the new value
echo "new memory: ".$new_memory; // echo the new value
// Will display:
// original memory: 64
// new memory: 128
?>
You have to place the ini_set('memory_limit','128M');
at the top of the file or at least before any echo.
As for me, suhosin wasn't the solution because it doesn't even appear in my phpinfo(), but this worked:
<?php
ini_set('memory_limit','2048M'); // set at the top of the file
(...)
?>
It is simpler when you have a lot of image buttons, and you don't want to write xml-s for every button.
Kotlin Version:
fun buttonEffect(button: View) {
button.setOnTouchListener { v, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> {
v.background.setColorFilter(-0x1f0b8adf, PorterDuff.Mode.SRC_ATOP)
v.invalidate()
}
MotionEvent.ACTION_UP -> {
v.background.clearColorFilter()
v.invalidate()
}
}
false
}
}
Java Version:
public static void buttonEffect(View button){
button.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
v.getBackground().setColorFilter(0xe0f47521,PorterDuff.Mode.SRC_ATOP);
v.invalidate();
break;
}
case MotionEvent.ACTION_UP: {
v.getBackground().clearColorFilter();
v.invalidate();
break;
}
}
return false;
}
});
}
I'm looking for the fastest way of inserting into Entity Framework
There are some third-party libraries supporting Bulk Insert available:
See: Entity Framework Bulk Insert library
Be careful, when choosing a bulk insert library. Only Entity Framework Extensions supports all kind of associations and inheritances and it's the only one still supported.
Disclaimer: I'm the owner of Entity Framework Extensions
This library allows you to perform all bulk operations you need for your scenarios:
Example
// Easy to use
context.BulkSaveChanges();
// Easy to customize
context.BulkSaveChanges(bulk => bulk.BatchSize = 100);
// Perform Bulk Operations
context.BulkDelete(customers);
context.BulkInsert(customers);
context.BulkUpdate(customers);
// Customize Primary Key
context.BulkMerge(customers, operation => {
operation.ColumnPrimaryKeyExpression =
customer => customer.Code;
});
Try the following
double hours = (b-a).TotalHours;
If you just want the hour difference excluding the difference in days you can use the following
int hours = (b-a).Hours;
The difference between these two properties is mainly seen when the time difference is more than 1 day. The Hours property will only report the actual hour difference between the two dates. So if two dates differed by 100 years but occurred at the same time in the day, hours would return 0. But TotalHours will return the difference between in the total amount of hours that occurred between the two dates (876,000 hours in this case).
The other difference is that TotalHours will return fractional hours. This may or may not be what you want. If not, Math.Round can adjust it to your liking.
You can use the -S
flag to read from std input. Find below an example:
function shutd()
{
echo "mySuperSecurePassword" | sudo -S shutdown -h now
}
Pandas DataFrame columns are Pandas Series when you pull them out, which you can then call x.tolist()
on to turn them into a Python list. Alternatively you cast it with list(x)
.
import pandas as pd
data_dict = {'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'two': pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(data_dict)
print(f"DataFrame:\n{df}\n")
print(f"column types:\n{df.dtypes}")
col_one_list = df['one'].tolist()
col_one_arr = df['one'].to_numpy()
print(f"\ncol_one_list:\n{col_one_list}\ntype:{type(col_one_list)}")
print(f"\ncol_one_arr:\n{col_one_arr}\ntype:{type(col_one_arr)}")
Output:
DataFrame:
one two
a 1.0 1
b 2.0 2
c 3.0 3
d NaN 4
column types:
one float64
two int64
dtype: object
col_one_list:
[1.0, 2.0, 3.0, nan]
type:<class 'list'>
col_one_arr:
[ 1. 2. 3. nan]
type:<class 'numpy.ndarray'>
If you're using org.codehaus.jackson, this has been possible since 1.6. You can convert a JsonNode to a POJO with ObjectMapper#readValue
: http://jackson.codehaus.org/1.9.4/javadoc/org/codehaus/jackson/map/ObjectMapper.html#readValue(org.codehaus.jackson.JsonNode, java.lang.Class)
ObjectMapper mapper = new ObjectMapper();
JsonParser jsonParser = mapper.getJsonFactory().createJsonParser("{\"foo\":\"bar\"}");
JsonNode tree = jsonParser.readValueAsTree();
// Do stuff to the tree
mapper.readValue(tree, Foo.class);
update your CSS to the following: this should fix
.page {
width: 280px;
border:solid 1px blue;
overflow-x: auto;
}
Try using this npm package. This helped me decoding the res structure from my node while using passport-azure-ad
for integrating login using Microsoft account
https://www.npmjs.com/package/circular-json
You can stringify your circular structure by doing:
const str = CircularJSON.stringify(obj);
then you can convert it onto JSON using JSON parser
JSON.parse(str)
With Android Studio 1.4, the template project with boiler plate code sets Overlay
theme on your AppbarLayout and/or Toolbar. They are also set to be rendered behind the status bar by fitSystemWindow
attribute = true. This will cause only toolbar to be rendered directly below the status bar and everything else will rendered beneath the toolbar. So the solutions provided above won't work on their own. You will have to make the following changes.
Put the following code in your styles-21.xml file.
@android:color/transparent
Assign this theme to the activity containing the navigation drawer in the AndroidManifest.xml file.
This will make the Navigation drawer to render behind the transparent status bar.
I know this question is not about array of objects, but searchers do end up here.
so it's worth adding for future readers a proper ES6 way of merging and then removing duplicates
array of objects:
var arr1 = [ {a: 1}, {a: 2}, {a: 3} ];
var arr2 = [ {a: 1}, {a: 2}, {a: 4} ];
var arr3 = arr1.concat(arr2.filter( ({a}) => !arr1.find(f => f.a == a) ));
// [ {a: 1}, {a: 2}, {a: 3}, {a: 4} ]
A scalar always holds a single element. Whatever is in a scalar variable is always a scalar. A reference is a scalar value.
If you want to know if it is a reference, you can use ref
. If you want to know the reference type,
you can use the reftype
routine from Scalar::Util.
If you want to know if it is an object, you can use the blessed
routine from Scalar::Util. You should never care what the blessed package is, though. UNIVERSAL
has some methods to tell you about an object: if you want to check that it has the method you want to call, use can
; if you want to see that it inherits from something, use isa
; and if you want to see it the object handles a role, use DOES
.
If you want to know if that scalar is actually just acting like a scalar but tied to a class, try tied
. If you get an object, continue your checks.
If you want to know if it looks like a number, you can use looks_like_number
from Scalar::Util. If it doesn't look like a number and it's not a reference, it's a string. However, all simple values can be strings.
If you need to do something more fancy, you can use a module such as Params::Validate.
public class Permutation
{
public static void main(String[] args)
{
String str = "ABC";
int n = str.length();
Permutation permutation = new Permutation();
permutation.permute(str, 0, n-1);
}
/**
* permutation function
* @param str string to calculate permutation for
* @param l starting index
* @param r end index
*/
private void permute(String str, int l, int r)
{
if (l == r)
System.out.println(str);
else
{
for (int i = l; i <= r; i++)
{
str = swap(str,l,i);
permute(str, l+1, r);
str = swap(str,l,i);
}
}
}
/**
* Swap Characters at position
* @param a string value
* @param i position 1
* @param j position 2
* @return swapped string
*/
public String swap(String a, int i, int j)
{
char temp;
char[] charArray = a.toCharArray();
temp = charArray[i] ;
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}
}
This works as well:
select * from mde_product where cfn = 'A3D"&"R01'
you define &
as literal by enclosing is with double qoutes "&"
in the string.
You can't have a non-keyword argument after a keyword argument.
Make sure you re-arrange your function arguments like so:
def a(len1,til,hgt=len1,col=0):
system('mode con cols='+len1,'lines='+hgt)
system('title',til)
system('color',col)
a(64,"hi",25,"0b")
The simplest solution.
Thanks to my partner that gave me this answer.
You can set an onkeypress event on the input textbox like this:
onkeypress="validate(event)"
and then use regular expressions like this:
function validate(evt){
evt.value = evt.value.replace(/[^0-9]/g,"");
}
It will scan and remove any letter or sign different from number in the field.
if you handel this from dataBase try :
<img :src="baseUrl + 'path/path' + obj.key +'.png'">
My opinion,
Task.Delay()
is asynchronous. It doesn't block the current thread. You can still do other operations within current thread. It returns a Task return type (Thread.Sleep()
doesn't return anything ). You can check if this task is completed(use Task.IsCompleted
property) later after another time-consuming process.
Thread.Sleep()
doesn't have a return type. It's synchronous. In the thread, you can't really do anything other than waiting for the delay to finish.
As for real-life usage, I have been programming for 15 years. I have never used Thread.Sleep()
in production code. I couldn't find any use case for it.
Maybe that's because I mostly do web application development.
There is also BusterJS from Christian Johansen, the author of Test Driven Javascript Development and the Sinon framework. From the site:
Buster.JS is a new JavaScript testing framework. It does browser testing by automating test runs in actual browsers (think JsTestDriver), as well as Node.js testing.
The VirtualHost would look like this:
NameVirtualHost IP_Address:443
<VirtualHost IP_Address:443>
SSLEngine on
SSLCertificateFile /etc/pki/tls/certs/ca.crt # Where "ca" is the name of the Certificate
SSLCertificateKeyFile /etc/pki/tls/private/ca.key
ServerAdmin webmaster@domain_name.com
DocumentRoot /var/www/html
ServerName www.domain_name.com
ErrorLog logs/www.domain_name.com-error_log
CustomLog logs/www.domain_name.com-access_log common
</VirtualHost>
Unfortunately neither display:inline-block
nor width:0px
works in Internet Explorer up to version 8. I have not tried Internet Explorer 9. Much as I would like to ignore Internet Explorer, I can't.
The only option that works on Firefox and Internet Explorer 8 is float:left
. The only slight drawback is that you have to remember to use clear:both
on the element that follows the form. Of course, it will be very obvious if you forget ;-)
I was having the same problem and none if these worked for me. Here is what did work though...
app.factory('myService', function($http) {
var data = function (value) {
return $http.get(value);
}
return { data: data }
});
and then the function that uses it is...
vm.search = function(value) {
var recieved_data = myService.data(value);
recieved_data.then(
function(fulfillment){
vm.tags = fulfillment.data;
}, function(){
console.log("Server did not send tag data.");
});
};
The service isn't that necessary but I think its a good practise for extensibility. Most of what you will need for one will for any other, especially when using APIs. Anyway I hope this was helpful.
Another library that might be useful for HTML processing is jsoup. Jsoup tries to clean malformed HTML and allows html parsing in Java using jQuery like tag selector syntax.
The default dbpath for mongodb is /data/db
.
There is no default config file, so you will either need to specify this when starting mongod
with:
mongod --config /etc/mongodb.conf
.. or use a packaged install of MongoDB (such as for Redhat or Debian/Ubuntu) which will include a config file path in the service definition.
Note: to check the dbpath and command-line options for a running mongod
, connect via the mongo
shell and run:
db.serverCmdLineOpts()
In particular, if a custom dbpath
is set it will be the value of:
db.serverCmdLineOpts().parsed.dbpath // MongoDB 2.4 and older
db.serverCmdLineOpts().parsed.storage.dbPath // MongoDB 2.6+
$(document).ready(function(){_x000D_
$("#left").on('click', function (e) {_x000D_
e.stopPropagation();_x000D_
e.preventDefault();_x000D_
$('#left').hide("slide", { direction: "left" }, 500, function () {_x000D_
$('#right').show("slide", { direction: "right" }, 500);_x000D_
});_x000D_
});_x000D_
$("#right").on('click', function (e) {_x000D_
e.stopPropagation();_x000D_
e.preventDefault();_x000D_
$('#right').hide("slide", { direction: "right" }, 500, function () {_x000D_
$('#left').show("slide", { direction: "left" }, 500);_x000D_
});_x000D_
});_x000D_
_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
_x000D_
<div style="height:100%;width:100%;background:cyan" id="left">_x000D_
<h1>Hello im going left to hide and will comeback from left to show</h1>_x000D_
</div>_x000D_
<div style="height:100%;width:100%;background:blue;display:none" id="right">_x000D_
<h1>Hello im coming from right to sho and will go back to right to hide</h1>_x000D_
</div>
_x000D_
$("#btnOpenEditing").off('click');
$("#btnOpenEditing").on('click', function (e) {
e.stopPropagation();
e.preventDefault();
$('#mappingModel').hide("slide", { direction: "right" }, 500, function () {
$('#fsEditWindow').show("slide", { direction: "left" }, 500);
});
});
It will work like charm take a look at the demo.
Here is what I'm doing very easily: I modified my base.html file for my template and put that at the bottom:
{% if DJdata %}
<script type="text/javascript">
(function () {window.DJdata = {{DJdata|safe}};})();
</script>
{% endif %}
then when I want to use a variable in the javascript files, I create a DJdata dictionary and I add it to the context by a json : context['DJdata'] = json.dumps(DJdata)
Hope it helps!
Simplest solution:
Just add quotes, I really don't know why it's not auto-implemented by Spring boot when response type defined as application/json, but it works great.
@PostMapping("/create")
public String foo()
{
String result = "something"
return "\"" + result + "\"";
}
Here is a helper function:
def append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None,
truncate_sheet=False,
**to_excel_kwargs):
"""
Append a DataFrame [df] to existing Excel file [filename]
into [sheet_name] Sheet.
If [filename] doesn't exist, then this function will create it.
Parameters:
filename : File path or existing ExcelWriter
(Example: '/path/to/file.xlsx')
df : dataframe to save to workbook
sheet_name : Name of sheet which will contain DataFrame.
(default: 'Sheet1')
startrow : upper left cell row to dump data frame.
Per default (startrow=None) calculate the last row
in the existing DF and write to the next row...
truncate_sheet : truncate (remove and recreate) [sheet_name]
before writing DataFrame to Excel file
to_excel_kwargs : arguments which will be passed to `DataFrame.to_excel()`
[can be dictionary]
Returns: None
(c) [MaxU](https://stackoverflow.com/users/5741205/maxu?tab=profile)
"""
from openpyxl import load_workbook
# ignore [engine] parameter if it was passed
if 'engine' in to_excel_kwargs:
to_excel_kwargs.pop('engine')
writer = pd.ExcelWriter(filename, engine='openpyxl')
# Python 2.x: define [FileNotFoundError] exception if it doesn't exist
try:
FileNotFoundError
except NameError:
FileNotFoundError = IOError
try:
# try to open an existing workbook
writer.book = load_workbook(filename)
# get the last row in the existing Excel sheet
# if it was not specified explicitly
if startrow is None and sheet_name in writer.book.sheetnames:
startrow = writer.book[sheet_name].max_row
# truncate sheet
if truncate_sheet and sheet_name in writer.book.sheetnames:
# index of [sheet_name] sheet
idx = writer.book.sheetnames.index(sheet_name)
# remove [sheet_name]
writer.book.remove(writer.book.worksheets[idx])
# create an empty sheet [sheet_name] using old index
writer.book.create_sheet(sheet_name, idx)
# copy existing sheets
writer.sheets = {ws.title:ws for ws in writer.book.worksheets}
except FileNotFoundError:
# file does not exist yet, we will create it
pass
if startrow is None:
startrow = 0
# write out the new sheet
df.to_excel(writer, sheet_name, startrow=startrow, **to_excel_kwargs)
# save the workbook
writer.save()
NOTE: for Pandas < 0.21.0, replace sheet_name
with sheetname
!
Usage examples:
append_df_to_excel('d:/temp/test.xlsx', df)
append_df_to_excel('d:/temp/test.xlsx', df, header=None, index=False)
append_df_to_excel('d:/temp/test.xlsx', df, sheet_name='Sheet2', index=False)
append_df_to_excel('d:/temp/test.xlsx', df, sheet_name='Sheet2', index=False, startrow=25)
sELECT
TableName = t.name,
IndexName = ind.name,
--IndexId = ind.index_id,
ColumnId = ic.index_column_id,
ColumnName = col.name,
key_ordinal,
ind.type_desc
--ind.*,
--ic.*,
--col.*
FROM
sys.indexes ind
INNER JOIN
sys.index_columns ic ON ind.object_id = ic.object_id and ind.index_id = ic.index_id
INNER JOIN
sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id
INNER JOIN
sys.tables t ON ind.object_id = t.object_id
WHERE
ind.is_primary_key = 0
AND ind.is_unique = 0
AND ind.is_unique_constraint = 0
AND t.is_ms_shipped = 0
and t.name='CompanyReconciliation' --table name
and key_ordinal>0
ORDER BY
t.name, ind.name, ind.index_id, ic.index_column_id
Here is to share something I found on __import__
and importlib
while trying to solve this problem.
I am using Python 3.7.3.
When I try to get to the class d
in module a.b.c
,
mod = __import__('a.b.c')
The mod
variable refer to the top namespace a
.
So to get to the class d
, I need to
mod = getattr(mod, 'b') #mod is now module b
mod = getattr(mod, 'c') #mod is now module c
mod = getattr(mod, 'd') #mod is now class d
If we try to do
mod = __import__('a.b.c')
d = getattr(mod, 'd')
we are actually trying to look for a.d
.
When using importlib
, I suppose the library has done the recursive getattr
for us. So, when we use importlib.import_module
, we actually get a handle on the deepest module.
mod = importlib.import_module('a.b.c') #mod is module c
d = getattr(mod, 'd') #this is a.b.c.d
Very quick and simple and does exactly what you want
svn status | awk '{if($2 !~ /(config|\.ini)/ && !system("test -e \"" $2 "\"")) {print $2; system("rm -Rf \"" $2 "\"");}}'
The /(config|.ini)/ is for my own purposes.
And might be a good idea to add --no-ignore to the svn command
Multi-file variable scope example
Here I illustrate how static affects the scope of function definitions across multiple files.
a.c
#include <stdio.h>
/*
Undefined behavior: already defined in main.
Binutils 2.24 gives an error and refuses to link.
https://stackoverflow.com/questions/27667277/why-does-borland-compile-with-multiple-definitions-of-same-object-in-different-c
*/
/*int i = 0;*/
/* Works in GCC as an extension: https://stackoverflow.com/a/3692486/895245 */
/*int i;*/
/* OK: extern. Will use the one in main. */
extern int i;
/* OK: only visible to this file. */
static int si = 0;
void a() {
i++;
si++;
puts("a()");
printf("i = %d\n", i);
printf("si = %d\n", si);
puts("");
}
main.c
#include <stdio.h>
int i = 0;
static int si = 0;
void a();
void m() {
i++;
si++;
puts("m()");
printf("i = %d\n", i);
printf("si = %d\n", si);
puts("");
}
int main() {
m();
m();
a();
a();
return 0;
}
Compile and run:
gcc -c a.c -o a.o
gcc -c main.c -o main.o
gcc -o main main.o a.o
Output:
m()
i = 1
si = 1
m()
i = 2
si = 2
a()
i = 3
si = 1
a()
i = 4
si = 2
Interpretation
si
, one for each filei
As usual, the smaller the scope, the better, so always declare variables static
if you can.
In C programming, files are often used to represent "classes", and static
variables represent private static members of the class.
What standards say about it
C99 N1256 draft 6.7.1 "Storage-class specifiers" says that static
is a "storage-class specifier".
6.2.2/3 "Linkages of identifiers" says static
implies internal linkage
:
If the declaration of a file scope identifier for an object or a function contains the storage-class specifier static, the identifier has internal linkage.
and 6.2.2/2 says that internal linkage
behaves like in our example:
In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. Within one translation unit, each declaration of an identifier with internal linkage denotes the same object or function.
where "translation unit is a source file after preprocessing.
How GCC implements it for ELF (Linux)?
With the STB_LOCAL
binding.
If we compile:
int i = 0;
static int si = 0;
and disassemble the symbol table with:
readelf -s main.o
the output contains:
Num: Value Size Type Bind Vis Ndx Name
5: 0000000000000004 4 OBJECT LOCAL DEFAULT 4 si
10: 0000000000000000 4 OBJECT GLOBAL DEFAULT 4 i
so the binding is the only significant difference between them. Value
is just their offset into the .bss
section, so we expect it to differ.
STB_LOCAL
is documented on the ELF spec at http://www.sco.com/developers/gabi/2003-12-17/ch4.symtab.html:
STB_LOCAL Local symbols are not visible outside the object file containing their definition. Local symbols of the same name may exist in multiple files without interfering with each other
which makes it a perfect choice to represent static
.
Variables without static are STB_GLOBAL
, and the spec says:
When the link editor combines several relocatable object files, it does not allow multiple definitions of STB_GLOBAL symbols with the same name.
which is coherent with the link errors on multiple non static definitions.
If we crank up the optimization with -O3
, the si
symbol is removed entirely from the symbol table: it cannot be used from outside anyways. TODO why keep static variables on the symbol table at all when there is no optimization? Can they be used for anything? Maybe for debugging.
See also
static
functions: https://stackoverflow.com/a/30319812/895245static
with extern
, which does "the opposite": How do I use extern to share variables between source files?C++ anonymous namespaces
In C++, you might want to use anonymous namespaces instead of static, which achieves a similar effect, but further hides type definitions: Unnamed/anonymous namespaces vs. static functions
You need to add this code in your AppDelegate file, not in your Root View Controller
Or add the property Status bar is initially hidden in your plist file
Folks, in iOS 7+
please add this to your info.plist file, It will make the difference :)
UIStatusBarHidden UIViewControllerBasedStatusBarAppearance
For iOS 11.4+ and Xcode 9.4 +
Use this code either in one or all your view controllers
override var prefersStatusBarHidden: Bool { return true }
In general, whenever you get an error like Can't bind to 'xxx' since it isn't a known native property
, the most likely cause is forgetting to specify a component or a directive (or a constant that contains the component or the directive) in the directives
metadata array. Such is the case here.
Since you did not specify RouterLink
or the constant ROUTER_DIRECTIVES
– which contains the following:
export const ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkWithHref,
RouterLinkActive];
– in the directives
array, then when Angular parses
<a [routerLink]="['RoutingTest']">Routing Test</a>
it doesn't know about the RouterLink directive (which uses attribute selector routerLink
). Since Angular does know what the a
element is, it assumes that [routerLink]="..."
is a property binding for the a
element. But it then discovers that routerLink
is not a native property of a
elements, hence it throws the exception about the unknown property.
I've never really liked the ambiguity of the syntax. I.e., consider
<something [whatIsThis]="..." ...>
Just by looking at the HTML we can't tell if whatIsThis
is
something
something
We have to know which directives: [...]
are specified in the component's/directive's metadata in order to mentally interpret the HTML. And when we forget to put something into the directives
array, I feel this ambiguity makes it a bit harder to debug.
In my situation it was a forgotten component which locates in ViewHolder class but it wasn't located in layout file
If you're looking for something that behaves like an enumeration (because I see you are defining an object and attaching a sequential ID 0, 1, 2 and contains a name field that you don't want to misspell (e.g. name vs naaame), you're better off defining an enumeration because the sequential ID is taken care of automatically, and provides type verification for you out of the box.
enum TestStatus {
Available, // 0
Ready, // 1
Started, // 2
}
class Test {
status: TestStatus
}
var test = new Test();
test.status = TestStatus.Available; // type and spelling is checked for you,
// and the sequence ID is automatic
The values above will be automatically mapped, e.g. "0" for "Available", and you can access them using TestStatus.Available
. And Typescript will enforce the type when you pass those around.
You wanted an array of objects, (not exactly an object with keys "0", "1" and "2"), so let's define the type of the object, first, then a type of a containing array.
class TestStatus {
id: number
name: string
constructor(id, name){
this.id = id;
this.name = name;
}
}
type Statuses = Array<TestStatus>;
var statuses: Statuses = [
new TestStatus(0, "Available"),
new TestStatus(1, "Ready"),
new TestStatus(2, "Started")
]
My understanding is that, for example, you wrongly saved a file you had updated for testing purposes only. Then, when you run "git status" the file appears as "Modified" and you say some bad words. You just want the old version back and continue to work normally.
In that scenario you can just run the following command:
git checkout -- path/filename
To call a function inside a same controller in any laravel version follow as bellow
$role = $this->sendRequest('parameter');
// sendRequest is a public function
Use FQL instead, its a like SQL but for Facebook's data tables and easily covers data query you'de like to make. You won't have to use all of those /xx/xxx/xx calls, just know the tables and columns you are intereseted in.
$myQuery = "SELECT uid2 FROM friend WHERE uid1=me()";
$facebook->api( "/fql?q=" . urlencode($myQuery) )
Great interactive examples at http://developers.facebook.com/docs/reference/fql/
var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'
I'm using this function that find all images in my letter and attaches it to the message.
Parameters: Takes your HTML (which you want to send);
Return: The necessary HTML and headers, which you can use in mail()
;
Example usage:
define("DEFCALLBACKMAIL", "[email protected]"); // WIll be shown as "from".
$final_msg = preparehtmlmail($html); // give a function your html*
mail('[email protected]', 'your subject', $final_msg['multipart'], $final_msg['headers']);
// send email with all images from html attached to letter
function preparehtmlmail($html) {
preg_match_all('~<img.*?src=.([\/.a-z0-9:_-]+).*?>~si',$html,$matches);
$i = 0;
$paths = array();
foreach ($matches[1] as $img) {
$img_old = $img;
if(strpos($img, "http://") == false) {
$uri = parse_url($img);
$paths[$i]['path'] = $_SERVER['DOCUMENT_ROOT'].$uri['path'];
$content_id = md5($img);
$html = str_replace($img_old,'cid:'.$content_id,$html);
$paths[$i++]['cid'] = $content_id;
}
}
$boundary = "--".md5(uniqid(time()));
$headers .= "MIME-Version: 1.0\n";
$headers .="Content-Type: multipart/mixed; boundary=\"$boundary\"\n";
$headers .= "From: ".DEFCALLBACKMAIL."\r\n";
$multipart = '';
$multipart .= "--$boundary\n";
$kod = 'utf-8';
$multipart .= "Content-Type: text/html; charset=$kod\n";
$multipart .= "Content-Transfer-Encoding: Quot-Printed\n\n";
$multipart .= "$html\n\n";
foreach ($paths as $path) {
if(file_exists($path['path']))
$fp = fopen($path['path'],"r");
if (!$fp) {
return false;
}
$imagetype = substr(strrchr($path['path'], '.' ),1);
$file = fread($fp, filesize($path['path']));
fclose($fp);
$message_part = "";
switch ($imagetype) {
case 'png':
case 'PNG':
$message_part .= "Content-Type: image/png";
break;
case 'jpg':
case 'jpeg':
case 'JPG':
case 'JPEG':
$message_part .= "Content-Type: image/jpeg";
break;
case 'gif':
case 'GIF':
$message_part .= "Content-Type: image/gif";
break;
}
$message_part .= "; file_name = \"$path\"\n";
$message_part .= 'Content-ID: <'.$path['cid'].">\n";
$message_part .= "Content-Transfer-Encoding: base64\n";
$message_part .= "Content-Disposition: inline; filename = \"".basename($path['path'])."\"\n\n";
$message_part .= chunk_split(base64_encode($file))."\n";
$multipart .= "--$boundary\n".$message_part."\n";
}
$multipart .= "--$boundary--\n";
return array('multipart' => $multipart, 'headers' => $headers);
}
There used to be a statement in the SQLite documentation that the practical size limit of a database file was a few dozen GB:s. That was mostly due to the need for SQLite to "allocate a bitmap of dirty pages" whenever you started a transaction. Thus 256 byte of RAM were required for each MB in the database. Inserting into a 50 GB DB-file would require a hefty (2^8)*(2^10)=2^18=256 MB of RAM.
But as of recent versions of SQLite, this is no longer needed. Read more here.
For the first rule,
Click "greater than", then in the value option box, click on the cell criteria you want it to be less than, than use the format drop-down to select your color.
For the second,
Click "less than", then in the value option box, type "=.9*" and then click the cell criteria, then use the formatting just like step 1.
For the third,
Same as the second, except your formula is =".8*" rather than .9.
Personally, window.postMessage
is the most reliable way that I've found for modern browsers. You do have to do a slight bit more work to make sure you're not leaving yourself open to XSS attacks, but it's a reasonable tradeoff.
There are also several plugins for the popular Javascript toolkits out there that wrap window.postMessage
that provide similar functionality to older browsers using the other methods discussed above.
I just solved this kind of a problem. What I've learned is:
my.cnf
and set the bind-address = your.mysql.server.address
under [mysqld]
check if it's running
mysql -u root -h your.mysql.server.address –p
create a user (usr or anything) with % as domain and grant her access to the database in question.
mysql> CREATE USER 'usr'@'%' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON testDb.* TO 'monty'@'%' WITH GRANT OPTION;
open firewall for port 3306 (you can use iptables. make sure to open port for eithe reveryone, or if you're in tight securety, then only allow the client address)
you should be able to now connect mysql server form your client server php script.
One of the key differences is that Websites compile dynamically and create on-the-fly assemblies. Web applicaitons compile into one large assembly.
The distinction between the two has been done away with in Visual Studio 2008.
You cant simply (directly) convert the datareader to list.
You have to loop through all the elements in datareader and insert into list
below the sample code
using (drOutput)
{
System.Collections.Generic.List<CustomerEntity > arrObjects = new System.Collections.Generic.List<CustomerEntity >();
int customerId = drOutput.GetOrdinal("customerId ");
int CustomerName = drOutput.GetOrdinal("CustomerName ");
while (drOutput.Read())
{
CustomerEntity obj=new CustomerEntity ();
obj.customerId = (drOutput[customerId ] != Convert.DBNull) ? drOutput[customerId ].ToString() : null;
obj.CustomerName = (drOutput[CustomerName ] != Convert.DBNull) ? drOutput[CustomerName ].ToString() : null;
arrObjects .Add(obj);
}
}
You can use this full code for your problem. For more details you can check it on appucoder.com
class FileDemoTwo{
public static void main(String args[])throws Exception{
FileDemoTwo ob = new FileDemoTwo();
BufferedReader in = new BufferedReader(new FileReader("read.txt"));
String str;
List<String> list = new ArrayList<String>();
while((str =in.readLine()) != null ){
list.add(str);
}
String[] stringArr = list.toArray(new String[0]);
System.out.println(" "+Arrays.toString(stringArr));
}
}
Try this code which makes use of a cross product:
public bool isLeft(Point a, Point b, Point c){
return ((b.X - a.X)*(c.Y - a.Y) - (b.Y - a.Y)*(c.X - a.X)) > 0;
}
Where a = line point 1; b = line point 2; c = point to check against.
If the formula is equal to 0, the points are colinear.
If the line is horizontal, then this returns true if the point is above the line.
If the array is NSArray you can use the adding
function to add any object at the end of the array, like this:
Swift 4.2
var myArray: NSArray = []
let firstElement: String = "First element"
let secondElement: String = "Second element"
// Process to add the elements to the array
myArray.adding(firstElement)
myArray.adding(secondElement)
Result:
print(myArray)
// ["First element", "Second element"]
That is a very simple way, regards!
You could use the removeAttr method, if you want to delete all the inline style you added manually with javascript. It's better to use CSS classes but you never know.
$("#displayPanel div").removeAttr("style")
Ways to hide Navigation Bar in Swift:
self.navigationController?.setNavigationBarHidden(true, animated: true)
self.navigationController?.navigationBar.isHidden = true
self.navigationController?.isNavigationBarHidden = true
Sure you can simply use two sliders overlaying each other and add a bit of javascript (actually not more than 5 lines) that the selectors are not exceeding the min/max values (like in @Garys) solution.
Attached you'll find a short snippet adapted from a current project including some CSS3 styling to show what you can do (webkit only). I also added some labels to display the selected values.
It uses JQuery but a vanillajs version is no magic though.
@Update: The code below was just a proof of concept. Due to many requests I've added a possible solution for Mozilla Firefox (without changing the original code). You may want to refractor the code below before using it.
(function() {
function addSeparator(nStr) {
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + '.' + '$2');
}
return x1 + x2;
}
function rangeInputChangeEventHandler(e){
var rangeGroup = $(this).attr('name'),
minBtn = $(this).parent().children('.min'),
maxBtn = $(this).parent().children('.max'),
range_min = $(this).parent().children('.range_min'),
range_max = $(this).parent().children('.range_max'),
minVal = parseInt($(minBtn).val()),
maxVal = parseInt($(maxBtn).val()),
origin = $(this).context.className;
if(origin === 'min' && minVal > maxVal-5){
$(minBtn).val(maxVal-5);
}
var minVal = parseInt($(minBtn).val());
$(range_min).html(addSeparator(minVal*1000) + ' €');
if(origin === 'max' && maxVal-5 < minVal){
$(maxBtn).val(5+ minVal);
}
var maxVal = parseInt($(maxBtn).val());
$(range_max).html(addSeparator(maxVal*1000) + ' €');
}
$('input[type="range"]').on( 'input', rangeInputChangeEventHandler);
})();
_x000D_
body{
font-family: sans-serif;
font-size:14px;
}
input[type='range'] {
width: 210px;
height: 30px;
overflow: hidden;
cursor: pointer;
outline: none;
}
input[type='range'],
input[type='range']::-webkit-slider-runnable-track,
input[type='range']::-webkit-slider-thumb {
-webkit-appearance: none;
background: none;
}
input[type='range']::-webkit-slider-runnable-track {
width: 200px;
height: 1px;
background: #003D7C;
}
input[type='range']:nth-child(2)::-webkit-slider-runnable-track{
background: none;
}
input[type='range']::-webkit-slider-thumb {
position: relative;
height: 15px;
width: 15px;
margin-top: -7px;
background: #fff;
border: 1px solid #003D7C;
border-radius: 25px;
z-index: 1;
}
input[type='range']:nth-child(1)::-webkit-slider-thumb{
z-index: 2;
}
.rangeslider{
position: relative;
height: 60px;
width: 210px;
display: inline-block;
margin-top: -5px;
margin-left: 20px;
}
.rangeslider input{
position: absolute;
}
.rangeslider{
position: absolute;
}
.rangeslider span{
position: absolute;
margin-top: 30px;
left: 0;
}
.rangeslider .right{
position: relative;
float: right;
margin-right: -5px;
}
/* Proof of concept for Firefox */
@-moz-document url-prefix() {
.rangeslider::before{
content:'';
width:100%;
height:2px;
background: #003D7C;
display:block;
position: relative;
top:16px;
}
input[type='range']:nth-child(1){
position:absolute;
top:35px !important;
overflow:visible !important;
height:0;
}
input[type='range']:nth-child(2){
position:absolute;
top:35px !important;
overflow:visible !important;
height:0;
}
input[type='range']::-moz-range-thumb {
position: relative;
height: 15px;
width: 15px;
margin-top: -7px;
background: #fff;
border: 1px solid #003D7C;
border-radius: 25px;
z-index: 1;
}
input[type='range']:nth-child(1)::-moz-range-thumb {
transform: translateY(-20px);
}
input[type='range']:nth-child(2)::-moz-range-thumb {
transform: translateY(-20px);
}
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="rangeslider">
<input class="min" name="range_1" type="range" min="1" max="100" value="10" />
<input class="max" name="range_1" type="range" min="1" max="100" value="90" />
<span class="range_min light left">10.000 €</span>
<span class="range_max light right">90.000 €</span>
</div>
_x000D_
I agree with Greg that the log is the best place to start. We've experienced something similar and the fix was to ensure that admins have full permissions to the registry location HKLM\System\CurrentControlSet\Control\WMI\Security prior to starting the installation. HTH.
In some cases, I could prevent Eclipse from crashing during startup by deleting a .snap file in your workspace meta-data (.metadata/.plugins/org.eclipse.core.resources/.snap).
See also https://bugs.eclipse.org/bugs/show_bug.cgi?id=149121 (the bug has been closed, but happened to me recently)
The default formatting is not very useful, in my opinion. I prefer ISO8601 as it's sortable, relatively compact and widely recognized:
>> require 'time'
=> true
>> Time.now.utc.iso8601
=> "2011-07-28T23:14:04Z"
Use this CSS:
background-size: 100% 100%
Long story short: you set some dimensions and let NumPy set the remaining(s).
(userDim1, userDim2, ..., -1) -->>
(userDim1, userDim1, ..., TOTAL_DIMENSION - (userDim1 + userDim2 + ...))
Another C# example. I just made an extension method for it.
public static string GetCellFromTable(this IWebElement table, int rowIndex, int columnIndex)
{
return table.FindElements(By.XPath("./tbody/tr"))[rowIndex].FindElements(By.XPath("./td"))[columnIndex].Text;
}
pure javascript no jQuery
function sah() {_x000D_
$("#div2").attr("disabled", "disabled").off('click');_x000D_
var x1=$("#div2").hasClass("disabledDiv");_x000D_
_x000D_
(x1==true)?$("#div2").removeClass("disabledDiv"):$("#div2").addClass("disabledDiv");_x000D_
sah1(document.getElementById("div1"));_x000D_
_x000D_
}_x000D_
_x000D_
function sah1(el) {_x000D_
try {_x000D_
el.disabled = el.disabled ? false : true;_x000D_
} catch (E) {}_x000D_
if (el.childNodes && el.childNodes.length > 0) {_x000D_
for (var x = 0; x < el.childNodes.length; x++) {_x000D_
sah1(el.childNodes[x]);_x000D_
}_x000D_
}_x000D_
}
_x000D_
#div2{_x000D_
padding:5px 10px;_x000D_
background-color:#777;_x000D_
width:150px;_x000D_
margin-bottom:20px;_x000D_
}_x000D_
.disabledDiv {_x000D_
pointer-events: none;_x000D_
opacity: 0.4;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>_x000D_
<div id="div1">_x000D_
<div id="div2" onclick="alert('Hello')">Click me</div>_x000D_
<input type="text" value="SAH Computer" />_x000D_
<br />_x000D_
<input type="button" value="SAH Computer" />_x000D_
<br />_x000D_
<input type="radio" name="sex" value="Male" />Male_x000D_
<Br />_x000D_
<input type="radio" name="sex" value="Female" />Female_x000D_
<Br />_x000D_
</div>_x000D_
<Br />_x000D_
<Br />_x000D_
<input type="button" value="Click" onclick="sah()" />
_x000D_
functional requirements are the main things that the user expects from the software for example if the application is a banking application that application should be able to create a new account, update the account, delete an account, etc. functional requirements are detailed and are specified in the system design
Non-functional requirement are not straight forward the requirement of the system rather it is related to usability( in some way ) for example for a banking application a major non-functional requirement will be available the application should be available 24/7 with no downtime if possible.
wmic OS get TotalVisibleMemorySize /Value
Note not TotalPhysicalMemory
as suggested elsewhere
I found the simplest solution:
git commit -am'save'
That's all,you will work around git commit message stuff.
you can even save that commend to a bash or other stuff to make it more simple.
Our team members always write those messages,but almost no one will see those message again.
Commit message is a time-kill stuff at least in our team,so we ignore it.
There is no string
type in C
. You have to use char arrays.
By the way your code will not work ,because the size of the array should allow for the whole array to fit in plus one additional zero terminating character.
You can use this approach to get the data from all the columns except one:-
Something like this:
SELECT * INTO #TemporaryTable FROM YourTableName
ALTER TABLE #TemporaryTable DROP COLUMN Columnwhichyouwanttoremove
SELECT * FROM #TemporaryTable
DROP TABLE #TemporaryTable
you also use preg_replace_callback
function . and this function is identical to its sibling preg_replace
except for it can take a callback function which gives you more control on how you manipulate your output.
$str = "this is a string";
echo preg_replace_callback(
'/\s+/',
function ($matches) {
return "";
},
$str
);
You can use it like this in template without any filters
{{ car.date_of_manufacture.strftime('%Y-%m-%d') }}
One thing that wasn't mentioned here (but kept me from running keytool altogether) was that you need to run the Command Prompt as Administrator.
Just wanted to share it...
I had a similar issue that led me to this question. In my browser debugger I was getting this error message:
Access to fetch at 'http://localhost:8081/index.delta?platform=android&dev=true&minify=false' from origin 'http://127.0.0.1:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
It took me awhile to realize I was using 127.0.0.1:8081
instead of localhost:8081
for my debugger.
To fix it, I simply had to change Chrome from:
http://127.0.0.1:8081/debugger-ui/
to
http://localhost:8081/debugger-ui/
Create a small function and use it anywhere
public SqlConnection con = "Your connection string";
public void gridviewUpdate()
{
con.Open();
string select = "SELECT * from table_name";
SqlDataAdapter da = new SqlDataAdapter(select, con);
DataSet ds = new DataSet();
da.Fill(ds, "table_name");
datagridview.DataSource = ds;
datagridview.DataMember = "table_name";
con.Close();
}
Shutdown Hooks are unstarted threads that are registered with Runtime.addShutdownHook().JVM does not give any guarantee on the order in which shutdown hooks are started.For more info refer http://techno-terminal.blogspot.in/2015/08/shutdown-hooks.html
You actually do not have to wait a full second for each request. I found that if I wait 200 miliseconds between each request I am able to avoid the OVER_QUERY_LIMIT response and the user experience is passable. With this solution you can load 20 items in 4 seconds.
$(items).each(function(i, item){
setTimeout(function(){
geoLocate("my address", function(myLatlng){
...
});
}, 200 * i);
}
window.onload = function() {
var userImage = document.getElementById('imageOtherUser');
var hangoutButton = document.getElementById("hangoutButtonId");
userImage.onclick = function() {
hangoutButton.click(); // this will trigger the click event
};
};
this will do the trick
Modern IPython uses the "--matplotlib
" argument with an optional backend parameter. It defaults to "auto", which is usually good enough on Mac and Windows. I haven't tested it on Ubuntu or any other Linux distribution, but I would expect it to work.
ipython --matplotlib
Try this code:
using System;
namespace Array
{
class Program
{
static void Main()
{
int[] number = new int[] {5, 5, 6, 7};
int sum = 0;
for (int i = 0; i <number.Length; i++)
{
sum += number[i];
}
Console.WriteLine(sum);
}
}
}
The result is:
23
This answers a different question:
If trying to figure out if an OBJECT (not class) has a property,
OBJECT.GetType().GetProperty("PROPERTY") != null
returns true if (but not only if) the property exists.
In my case, I was in an ASP.NET MVC Partial View and wanted to render something if either the property did not exist, or the property (boolean) was true.
@if ((Model.GetType().GetProperty("AddTimeoffBlackouts") == null) ||
Model.AddTimeoffBlackouts)
helped me here.
Edit: Nowadays, it's probably smart to use the nameof
operator instead of the stringified property name.
Unrelated, I'm sure, but do wrap your IDisposable
objects in using
blocks to ensure proper disposal:
using System;
using System.Net;
using System.IO;
namespace ConsoleProgram
{
public class Class1
{
private const string URL = "https://sub.domain.com/objects.json?api_key=123";
private const string DATA = @"{""object"":{""name"":""Name""}}";
static void Main(string[] args)
{
Class1.CreateObject();
}
private static void CreateObject()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = DATA.Length;
using (Stream webStream = request.GetRequestStream())
using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
{
requestWriter.Write(DATA);
}
try
{
WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream() ?? Stream.Null)
using (StreamReader responseReader = new StreamReader(webStream))
{
string response = responseReader.ReadToEnd();
Console.Out.WriteLine(response);
}
}
catch (Exception e)
{
Console.Out.WriteLine("-----------------");
Console.Out.WriteLine(e.Message);
}
}
}
}
There are two answers above up-to-now and they are both long (and tl;dr too short IMHO), so I write summary from my experience starting to use new java.time library (applicable as noted in other answers to Java version 8+). ISO 8601 sets standard way to write dates: YYYY-MM-DD
so the format of date-time is only as below (could be 0, 3, 6 or 9 digits for milliseconds) and no formatting string necessary:
import java.time.Instant;
public static void main(String[] args) {
String date="2010-10-02T12:23:23Z";
try {
Instant myDate = Instant.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I did not need it, but as getting year is in code from the question, then:
it is trickier, cannot be done from Instant
directly, can be done via Calendar
in way of questions Get integer value of the current year in Java and Converting java.time to Calendar but IMHO as format is fixed substring is more simple to use:
myDate.toString().substring(0,4);
There are two options:
A: You care about retaining array order:
a = append(a[:i], a[i+1:]...)
// or
a = a[:i+copy(a[i:], a[i+1:])]
B: You don't care about retaining order (this is probably faster):
a[i] = a[len(a)-1] // Replace it with the last one. CAREFUL only works if you have enough elements.
a = a[:len(a)-1] // Chop off the last one.
See the link to see implications re memory leaks if your array is of pointers.
SQL Server also accepts the simpler notation of:
SELECT A.F,
B.G,
C.H
FROM TABLE_A A,
TABLE_B B,
TABLE_C C
WHERE A.X = B.X
AND B.Y = C.Y
Using this simpler notation, one does not need to bother about the difference between inner and cross joins. Instead of two "ON" clauses, there is a single "WHERE" clause that does the job. If you have any difficulty in figuring out which "JOIN" "ON" clauses go where, abandon the "JOIN" notation and use the simpler one above.
It is not cheating.
I use NPOI for all my Excel needs.
Comes with a solution of examples for many common Excel tasks.
string DemoLimit = "02/28/2018";
string pattern = "MM/dd/yyyy";
CultureInfo enUS = new CultureInfo("en-US");
DateTime.TryParseExact(DemoLimit, pattern, enUS,
DateTimeStyles.AdjustToUniversal, out datelimit);
For more https://msdn.microsoft.com/en-us/library/ms131044(v=vs.110).aspx
There seems to be a syntactically simpler way, and therefore easier to remember, as opposed to the proposed solutions. I'm assuming that the column is called 'meta' in a dataframe df:
df2 = pd.DataFrame(df['meta'].str.split().values.tolist())
First()
FirstOrDefault()
We have an UserInfos table, which have some records as shown below. On the basis of this table below I have created example...
How to use First()
var result = dc.UserInfos.First(x => x.ID == 1);
There is only one record where ID== 1. Should return this record
ID: 1 First Name: Manish Last Name: Dubey Email: [email protected]
var result = dc.UserInfos.First(x => x.FName == "Rahul");
There are multiple records where FName == "Rahul". First record should be return.
ID: 7 First Name: Rahul Last Name: Sharma Email: [email protected]
var result = dc.UserInfos.First(x => x.ID ==13);
There is no record with ID== 13. An error should be occur.
InvalidOperationException: Sequence contains no elements
How to Use FirstOrDefault()
var result = dc.UserInfos.FirstOrDefault(x => x.ID == 1);
There is only one record where ID== 1. Should return this record
ID: 1 First Name: Manish Last Name: Dubey Email: [email protected]
var result = dc.UserInfos.FirstOrDefault(x => x.FName == "Rahul");
There are multiple records where FName == "Rahul". First record should be return.
ID: 7 First Name: Rahul Last Name: Sharma Email: [email protected]
var result = dc.UserInfos.FirstOrDefault(x => x.ID ==13);
There is no record with ID== 13. The return value is null
Hope it will help you to understand when to use First()
or FirstOrDefault()
.
I would echo the Json.NET library, which can transform the JSON response into a XML document. With the XML document, you can easily query with XPath and extract the data you need. I find this pretty useful.