new WindowSettings();
You just closed a brand new instance of the form that wasn't visible in the first place.
You need to close the original instance of the form by accepting it as a constructor parameter and storing it in a field.
The reason to make an App with no activity or service could be making a Homescreen Widget app that doesn't need to be started.
Once you start a project don't create any activities. After you created the project just hit run. Android studio will say No default activity found
.
Click Edit Configuration (From the Run menu) and in the Launch option part set the Launch value to Nothing.
Then click ok and run the App.
(Since there is no launcher activity, No app will be show in the Apps menu.).
Technically a Tier can be a kind of minimum environment required for the code to run.
E.g. hypothetically a 3-tier app can be running on
1 physical machine with 3 virtual machines with no OS.
(That was a 3-(hardware)tier app)
1 physical machine with 3 virtual machines with 3 different/same OSes
(That was a 3-(OS)tier app)
1 physical machine with 1 virtual machine with 1 OS but 3 AppServers
(That was a 3-(AppServer)tier app)
1 physical machine with 1 virtual machine with 1 OS with 1 AppServer but 3 DBMS
(That was a 3-(DBMS)tier app)
1 physical machine with 1 virtual machine with 1 OS with 1 AppServers and 1 DBMS but 3 Excel workbooks.
(That was a 3-(AppServer)tier app)
Excel workbook is the minimum required environment for VBA code to run.
Those 3 workbooks can sit on a single physical computer or multiple.
I have noticed that in practice people mean "OS Tier" when they say "Tier" in the app description context.
That is if an app runs on 3 separate OS then its a 3-Tier app.
So a pedantically correct way describing an app would be
"1-to-3-Tier capable, running on 2 Tiers" app.
:)
Layers are just types of code in respect to the functional separation of duties withing the app (e.g. Presentation, Data , Security etc.)
By the time script is executed, document
element is not available yet, because script
itself is in the head
. While it's a valid solution to keep script
in head
and render on DOMContentLoaded
event, it's even better to put your script
at the very bottom of the body
and render root component to a div
before it like this:
<html>
<head>
</head>
<body>
<div id="root"></div>
<script src="/bundle.js"></script>
</body>
</html>
and in the bundle.js
, call:
React.render(<App />, document.getElementById('root'));
You should always render to a nested div
instead of body
. Otherwise, all sorts of third-party code (Google Font Loader, browser plugins, whatever) can modify the body
DOM node when React doesn't expect it, and cause weird errors that are very hard to trace and debug. Read more about this issue.
The nice thing about putting script
at the bottom is that it won't block rendering until script load in case you add React server rendering to your project.
React.render
is deprecated, useReactDOM.render
instead.
Example:
import ReactDOM from 'react-dom';
ReactDOM.render(<App />, document.getElementById('root'));
These solutions are working in case when target database is blank. In case when both databases already have some data you need something more complicated http://byalexblog.net/merge-sql-databases
This was not as straightforward as I would have hoped. You need to use enumerate to keep track of how many columns you have. Then use that counter to look up the name of the column. The accepted answer does not show you how to access the column names dynamically.
for row in df.itertuples(index=False, name=None):
for k,v in enumerate(row):
print("column: {0}".format(df.columns.values[k]))
print("value: {0}".format(v)
$('#field-function_purpose')
will get you the element with ID field-function_purpose
, which is your div element. text()
returns you the content of the div.
var x = $('#field-function_purpose').text();
Summary
In context of deep learning the logits layer means the layer that feeds in to softmax (or other such normalization). The output of the softmax are the probabilities for the classification task and its input is logits layer. The logits layer typically produces values from -infinity to +infinity and the softmax layer transforms it to values from 0 to 1.
Historical Context
Where does this term comes from? In 1930s and 40s, several people were trying to adapt linear regression to the problem of predicting probabilities. However linear regression produces output from -infinity to +infinity while for probabilities our desired output is 0 to 1. One way to do this is by somehow mapping the probabilities 0 to 1 to -infinity to +infinity and then use linear regression as usual. One such mapping is cumulative normal distribution that was used by Chester Ittner Bliss in 1934 and he called this "probit" model, short for "probability unit". However this function is computationally expensive while lacking some of the desirable properties for multi-class classification. In 1944 Joseph Berkson used the function log(p/(1-p))
to do this mapping and called it logit, short for "logistic unit". The term logistic regression derived from this as well.
The Confusion
Unfortunately the term logits is abused in deep learning. From pure mathematical perspective logit is a function that performs above mapping. In deep learning people started calling the layer "logits layer" that feeds in to logit function. Then people started calling the output values of this layer "logit" creating the confusion with logit the function.
TensorFlow Code
Unfortunately TensorFlow code further adds in to confusion by names like tf.nn.softmax_cross_entropy_with_logits
. What does logits mean here? It just means the input of the function is supposed to be the output of last neuron layer as described above. The _with_logits
suffix is redundant, confusing and pointless. Functions should be named without regards to such very specific contexts because they are simply mathematical operations that can be performed on values derived from many other domains. In fact TensorFlow has another similar function sparse_softmax_cross_entropy
where they fortunately forgot to add _with_logits
suffix creating inconsistency and adding in to confusion. PyTorch on the other hand simply names its function without these kind of suffixes.
Reference
The Logit/Probit lecture slides is one of the best resource to understand logit. I have also updated Wikipedia article with some of above information.
In general the logs are in /YOUR_GLASSFISH_INSTALL/glassfish/domains/domain1/logs/
.
In NetBeans go to the "Services" tab open "Servers", right-click on your Glassfish instance and click "View Domain Server Log".
If this doesn't work right-click on the Glassfish instance and click "Properties", you can see the folder with the domains under "Domains folder". Go to this folder -> your-domain -> logs
If the server is already running you should see an Output
tab in NetBeans which is named similar to GlassFish Server x.x.x
You can also use cat
or tail -F
on /YOUR_GLASSFISH_INSTALL/glassfish/domains/domain1/logs/server.log
. If you are using a different domain then domain1
you have to adjust the path for that.
This promise will not resolve if the argument of JSON.parse() can not be parsed into a JSON object.
Promise.resolve(JSON.parse('{"key":"value"}')).then(json => {
console.log(json);
}).catch(err => {
console.log(err);
});
No, functions are not first class objects in java. You can do the same thing by implementing a handler class - this is how callbacks are implemented in the Swing etc.
There are however proposals for closures (the official name for what you're talking about) in future versions of java - Javaworld has an interesting article.
Found it! Merge command has a --squash
option
git checkout master
git merge --squash WIP
at this point everything is merged, possibly conflicted, but not committed. So I can now:
git add .
git commit -m "Merged WIP"
For Alpine Linux:
apk add openssl-dev
We're using OpenCV. It has lots of non-face-recognition stuff in there also, but, rest assured, it does do face-recognition.
Adding to what @KyleMit said, consider using:
col-md-*
classes for the larger outer columnscol-xs-*
classes for the smaller inner columnsThis will be useful when you view the page on different screen sizes.
On a small screen, the wrapping of larger outer columns will then happen while maintaining the smaller inner columns, if possible
Its simple If you are passing String X from A to B.
A--> B
In Activity A
1) Create Intent
2) Put data in intent using putExtra method of intent
3) Start activity
Intent i = new Intent(A.this, B.class);
i.putExtra("MY_kEY",X);
In Activity B
inside onCreate method
1) Get intent object
2) Get stored value using key(MY_KEY)
Intent intent = getIntent();
String result = intent.getStringExtra("MY_KEY");
This is the standard way to send data from A to B. you can send any data type, it could be int, boolean, ArrayList, String[]. Based on the datatype you stored in Activity as key, value pair retrieving method might differ like if you are passing int value then you will call
intent.getIntExtra("KEY");
You can even send Class objects too but for that, you have to make your class object implement the Serializable or Parceable interface.
How much data you can send across size. If data exceeds a certain amount in size then you might get TransactionTooLargeException. Suppose you are trying to send bitmap across the activity and if the size exceeds certain data size then you might see this exception.
If you don't want the full blown ActiveMQ, I recommend to consider RabbitMQ. RabbitMQ is lightweight messaging that uses the AMQP standard.
I recommend to also look into php-amqplib - a popular AMQP client library to access AMQP based message brokers.
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
foreach (X509Certificate2 certificate in store.Certificates){
//TODO's
}
Creating an Empty Dataframe with known Column Name:
Names = ['Col1','ActivityID','TransactionID']
df = pd.DataFrame(columns = Names)
Creating a dataframe from csv:
df = pd.DataFrame('...../file_name.csv')
Creating a dynamic filter to subset a dtaframe
:
i = 12
df[df['ActivitiID'] <= i]
Creating a dynamic filter to subset required columns of dtaframe
df[df['ActivityID'] == i][['TransactionID','ActivityID']]
You use ttk.Frame
, bg
option does not work for it. You should create style and apply it to the frame.
from tkinter import *
from tkinter.ttk import *
root = Tk()
s = Style()
s.configure('My.TFrame', background='red')
mail1 = Frame(root, style='My.TFrame')
mail1.place(height=70, width=400, x=83, y=109)
mail1.config()
root.mainloop()
I prefer the other methods already posted, but some people like to use:
case "$HOST" in
user1|node*)
echo "yes";;
*)
echo "no";;
esac
Edit:
I've added your alternates to the case statement above
In your edited version you have too many brackets. It should look like this:
if [[ $HOST == user1 || $HOST == node* ]];
Note: if you are looking for this, there's also a high chance you don't know how to install swifty
. Follow the instructions here.
sudo gem install cocoapods
cd ~/Path/To/Folder/Containing/ShowTracker
Next enter this command:
pod init
This will create a default Podfile
for your project. The Podfile
is where you define the dependencies your project relies on.
Type this command to open Podfile
using Xcode
for editing:
open -a Xcode Podfile
Add the Swifty
into the podfile
platform :ios, '8.0'
use_frameworks!
target 'MyApp' do
pod 'SwiftyJSON', '~> X.X.X'
end
var mURL = NSURL(string: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&units=metric")
if mURL == nil{
println("You are stupid")
return
}
var request = NSURLRequest(URL: mURL!)
NSURLConnection.sendAsynchronousRequest(
request,
queue: NSOperationQueue.mainQueue(),
completionHandler:{ (
response: NSURLResponse!,
data: NSData!,
error: NSError!) -> Void in
if data != nil {
var mJSON = JSON(data: data!)
if let current_conditions = mJSON["weather"][0]["description"].string {
println("Current conditions: " + current_conditions)
} else {
println("MORON!")
}
if let current_temperature = mJSON["main"]["temp"].double {
println("Temperature: "+ String(format:"%.f", current_temperature) + "°C"
} else {
println("MORON!")
}
}
})
As @Ian explained, the problem is that jQuery's click()
is not the same as the native one.
Therefore, consider using vanilla-js instead of jQuery:
var a = document.createElement('a');
a.href = "img.png";
a.download = "output.png";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
Had encountered this error and was able to figure out from log that the error is because of the disk space not being enough. All the data that was inserted in my case was not needed any longer. So I tried to FLUSHALL. Since redis-rdb-bgsave process was running, it was not allowing to FLUSH the data also. I followed below steps and was able to continue.
The process redis-rdb-bgsave was no longer running after the above steps.
For Python2.7(windows32) I installed only pywin32-223. And I wrote simple python`s code:
import win32api
import time
import win32con
# simulate the pressing-DOWN "ARROW key" of 200 times
for i in range(200):
time.sleep(0.5)
win32api.keybd_event(0x28, 0,0,0)
time.sleep(.05)
win32api.keybd_event(0x28,0 ,win32con.KEYEVENTF_KEYUP ,0)
It can be checked if you run the code and immediately go to the notepad window (where the text already exists) and place the cursor on the top line.
This other approach works well for me:
$("#myModal").on("show.bs.modal", function(e) {
var link = $(e.relatedTarget);
$(this).find(".modal-body").load(link.attr("href"));
});
Calling conventions defines how parameters are passed in the registers when calling or being called by other program. And the best source of these convention is in the form of ABI standards defined for each these hardware. For ease of compilation, the same ABI is also used by userspace and kernel program. Linux/Freebsd follow the same ABI for x86-64 and another set for 32-bit. But x86-64 ABI for Windows is different from Linux/FreeBSD. And generally ABI does not differentiate system call vs normal "functions calls". Ie, here is a particular example of x86_64 calling conventions and it is the same for both Linux userspace and kernel: http://eli.thegreenplace.net/2011/09/06/stack-frame-layout-on-x86-64/ (note the sequence a,b,c,d,e,f of parameters):
Performance is one of the reasons for these ABI (eg, passing parameters via registers instead of saving into memory stacks)
For ARM there is various ABI:
http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.subset.swdev.abi/index.html
ARM64 convention:
http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055b/IHI0055B_aapcs64.pdf
For Linux on PowerPC:
http://refspecs.freestandards.org/elf/elfspec_ppc.pdf
http://www.0x04.net/doc/elf/psABI-ppc64.pdf
And for embedded there is the PPC EABI:
http://www.freescale.com/files/32bit/doc/app_note/PPCEABI.pdf
This document is good overview of all the different conventions:
If you want to move the file in new path with keep original file name. use this:
$source_file = 'foo/image.jpg';
$destination_path = 'bar/';
rename($source_file, $destination_path . pathinfo($source_file, PATHINFO_BASENAME));
Oracle database object names maximum length is 30 bytes.
Object Name Rules: http://docs.oracle.com/database/121/SQLRF/sql_elements008.htm
If you want a more accurate measurement than the answer above:
set statistics time on
-- Query 1 goes here
-- Query 2 goes here
set statistics time off
The results will be in the Messages window.
Update (2015-07-29):
By popular request, I have written a code snippet that you can use to time an entire stored procedure run, rather than its components. Although this only returns the time taken by the last run, there are additional stats returned by sys.dm_exec_procedure_stats
that may also be of value:
-- Use the last_elapsed_time from sys.dm_exec_procedure_stats
-- to time an entire stored procedure.
-- Set the following variables to the name of the stored proc
-- for which which you would like run duration info
DECLARE @DbName NVARCHAR(128);
DECLARE @SchemaName SYSNAME;
DECLARE @ProcName SYSNAME=N'TestProc';
SELECT CONVERT(TIME(3),DATEADD(ms,ROUND(last_elapsed_time/1000.0,0),0))
AS LastExecutionTime
FROM sys.dm_exec_procedure_stats
WHERE OBJECT_NAME(object_id,database_id)=@ProcName AND
(OBJECT_SCHEMA_NAME(object_id,database_id)=@SchemaName OR @SchemaName IS NULL) AND
(DB_NAME(database_id)=@DbName OR @DbName IS NULL)
Assuming you're running on a Windows machine...
F12
keyScripts
, or Sources
, tab in the developer toolsThen during execution debugging you can do a handful of stepping motions...
F8
Continue: Will continue until the next breakpointF10
Step over: Steps over next function call (won't enter the
library)F11
Step into: Steps into the next function call (will
enter the library)Shift + F11
Step out: Steps out of the current
functionUpdate
After reading your updated post; to debug your code I would recommend temporarily using the jQuery Development Source Code. Although this doesn't directly solve your problem, it will allow you to debug more easily. For what you're trying to achieve I believe you'll need to step-in to the library, so hopefully the production code should help you decipher what's happening.
Your confusion stems from the fact that declared properties are not (necessarily named the same as) (instance) variables.
The expresion
indexPath.row
is equivalent to
[indexPath row]
and the assignment
delegate.myData = [myData objectAtIndex:indexPath.row];
is equivalent to
[delegate setMyData:[myData objectAtIndex:[indexPath row]]];
assuming standard naming for synthesised properties.
Furthermore, delegate
is probably declared as being of type id<SomeProtocol>
, i.e., the compiler hasn’t been able to provide actual type information for delegate
at that point, and the debugger is relying on information provided at compile-time. Since id
is a generic type, there’s no compile-time information about the instance variables in delegate
.
Those are the reasons why you don’t see myData
or row
as variables.
If you want to inspect the result of sending -row
or -myData
, you can use commands p
or po
:
p (NSInteger)[indexPath row]
po [delegate myData]
or use the expressions window (for instance, if you know your delegate
is of actual type MyClass *
, you can add an expression (MyClass *)delegate
, or right-click delegate
, choose View Value as…
and type the actual type of delegate
(e.g. MyClass *
).
That being said, I agree that the debugger could be more helpful:
There could be an option to tell the debugger window to use run-time type information instead of compile-time information. It'd slow down the debugger, granted, but would provide useful information;
Declared properties could be shown up in a group called properties and allow for (optional) inspection directly in the debugger window. This would also slow down the debugger because of the need to send a message/execute a method in order to get information, but would provide useful information, too.
You can always do something like this:
update mytable t
set SomeColumn = c.ComputedValue
from (select *, 42 as ComputedValue from mytable where id = 1) c
where t.id = c.id
You can now also use with statement inside update
update mytable t
set SomeColumn = c.ComputedValue
from (with abc as (select *, 43 as ComputedValue_new from mytable where id = 1
select *, 42 as ComputedValue, abc.ComputedValue_new from mytable n1
inner join abc on n1.id=abc.id) c
where t.id = c.id
In CSS3, there is now a native way to do this, without any of the hacks suggested in the existing answers: the caret-color
property.
There are a lot of things you can do to with the caret, as seen below. It can even be animated.
/* Keyword value */
caret-color: auto;
color: transparent;
color: currentColor;
/* <color> values */
caret-color: red;
caret-color: #5729e9;
caret-color: rgb(0, 200, 0);
caret-color: hsla(228, 4%, 24%, 0.8);
The caret-color
property is supported from Firefox 55, and Chrome 60. Support is also available in the Safari Technical Preview and in Opera (but not yet in Edge). You can view the current support tables here.
Perhaps this complementary example of "match" would be helpful.
Having two datasets:
first_dataset <- data.frame(name = c("John", "Luke", "Simon", "Gregory", "Mary"),
role = c("Audit", "HR", "Accountant", "Mechanic", "Engineer"))
second_dataset <- data.frame(name = c("Mary", "Gregory", "Luke", "Simon"))
If the name column contains only unique across collection values (across whole collection) then you can access row in other dataset by value of index returned by match
name_mapping <- match(second_dataset$name, first_dataset$name)
match returns proper row indexes of names in first_dataset from given names from second: 5 4 2 1
example here - accesing roles from first dataset by row index (by given name value)
for(i in 1:length(name_mapping)) {
role <- as.character(first_dataset$role[name_mapping[i]])
second_dataset$role[i] = role
}
===
second dataset with new column:
name role
1 Mary Engineer
2 Gregory Mechanic
3 Luke Supervisor
4 Simon Accountant
This turned out to be a very useful thread.
For those who are allergic to curly braces, here is the VB.NET version of Lucas' and Crake's answers:
Public Module ActionImage
<System.Runtime.CompilerServices.Extension()>
Function ActionImage(html As HtmlHelper, Action As String, RouteValues As Object, ImagePath As String, AltText As String) As MvcHtmlString
Dim url = New UrlHelper(html.ViewContext.RequestContext)
Dim imgHtml As String
'Build the <img> tag
Dim imgBuilder = New TagBuilder("img")
With imgBuilder
.MergeAttribute("src", url.Content(ImagePath))
.MergeAttribute("alt", AltText)
imgHtml = .ToString(TagRenderMode.Normal)
End With
Dim aHtml As String
'Build the <a> tag
Dim aBuilder = New TagBuilder("a")
With aBuilder
.MergeAttribute("href", url.Action(Action, RouteValues))
.InnerHtml = imgHtml 'Include the <img> tag inside
aHtml = aBuilder.ToString(TagRenderMode.Normal)
End With
Return MvcHtmlString.Create(aHtml)
End Function
<Extension()>
Function ActionImage(html As HtmlHelper, Action As String, Controller As String, RouteValues As Object, ImagePath As String, AltText As String) As MvcHtmlString
Dim url = New UrlHelper(html.ViewContext.RequestContext)
Dim imgHtml As String
'Build the <img> tag
Dim imgBuilder = New TagBuilder("img")
With imgBuilder
.MergeAttribute("src", url.Content(ImagePath))
.MergeAttribute("alt", AltText)
imgHtml = .ToString(TagRenderMode.Normal)
End With
Dim aHtml As String
'Build the <a> tag
Dim aBuilder = New TagBuilder("a")
With aBuilder
.MergeAttribute("href", url.Action(Action, Controller, RouteValues))
.InnerHtml = imgHtml 'Include the <img> tag inside
aHtml = aBuilder.ToString(TagRenderMode.Normal)
End With
Return MvcHtmlString.Create(aHtml)
End Function
End Module
The excellent library Type::Tiny provides an framework with which to build type-checking into your Perl code. What I show here is only the thinnest tip of the iceberg and is using Type::Tiny in the most simplistic and manual way.
Be sure to check out the Type::Tiny::Manual for more information.
use Types::Common::String qw< NonEmptyStr >;
if ( NonEmptyStr->check($name) ) {
# Do something here.
}
NonEmptyStr->($name); # Throw an exception if validation fails
You need to contain the three divs. Here is an example:
CSS
div.contain
{
margin:3%;
border: none;
height: auto;
width: auto;
float: left;
}
div.contain div
{
display:inline;
width:200px;
height:300px;
padding: 15px;
margin: auto;
border:1px solid red;
background-color:#fffff7;
-moz-border-radius:25px; /* Firefox */
border-radius:25px;
}
Note: border-radius attributes are optional and only work in CSS3 compliant browsers.
HTML
<div class="contain">
<div>Foo</div>
</div>
<div class="contain">
<div>Bar</div>
</div>
<div class="contain">
<div>Baz</div>
</div>
Note that the divs 'foo' 'bar' and 'baz' are each held within the 'contain' div.
For me, Not having a group by just returned empty result. So i guess having a group by for the having statement is pretty important
If you imagine the class hierarchy as a tree (as it is in Java), abstract classes can only be branches and final classes are those that can only be leafs. Classes that fall into neither of those categories can be both branches and leafs.
There's no violation of OO principles here, final is simply providing a nice symmetry.
In practice you want to use final if you want your objects to be immutable or if you're writing an API, to signal to the users of the API that the class is just not intended for extension.
I fixed it by added the jquery.slim.min.js after the jquery.min.js, as the Solution Sequence.
Problem Sequence
<script src="./vendor/jquery/jquery.min.js"></script>
<script src="./vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
Solution Sequence
<script src="./vendor/jquery/jquery.min.js"></script>
<script src="./vendor/jquery/jquery.slim.min.js"></script>
<script src="./vendor/jquery-easing/jquery.easing.min.js"></script>
I was having same error In ReactJS statless function while using ReactJs Hook useState. I wanted to set state of an object array , so if I use the following way
const [items , setItems] = useState([]);
and update the state like this:
const item = { id : new Date().getTime() , text : 'New Text' };
setItems([ item , ...items ]);
I was getting error:
Argument of type '{ id: number; text: any }' is not assignable to parameter of type 'never'
but if do it like this,
const [items , setItems] = useState([{}]);
Error is gone but there is an item at 0 index which don't have any data(don't want that).
so the solution I found is:
const [items , setItems] = useState([] as any);
If this is happening in a test class, make sure you haven't forgotten to annotate the class.
For example, in Spring Boot:
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTests {
....
Spring Boot continues to evolve. It is no longer required to use @RunWith
if you use the correct version of JUnit.
For @SpringBootTest
to work stand alone, you need to use @Test
from JUnit5 instead of JUnit4.
//import org.junit.Test; // JUnit4
import org.junit.jupiter.api.Test; // JUnit5
@SpringBootTest
public class MyTests {
....
If you get this configuration wrong your tests will compile, but @Autowired
and @Value
fields (for example) will be null
. Since Spring Boot operates by magic, you may have few avenues for directly debugging this failure.
dataString suggests the data is formatted in a string (and maybe delimted by a character).
$data = explode(",", $_POST['data']);
foreach($data as $d){
echo $d;
}
if dataString is not a string but infact an array (what your question indicates) use JSON.
Use Perl's URI::Escape
module and uri_escape
function in the second line of your bash script:
...
value="$(perl -MURI::Escape -e 'print uri_escape($ARGV[0]);' "$2")"
...
Edit: Fix quoting problems, as suggested by Chris Johnsen in the comments. Thanks!
You're looking for Action<T>
, which takes a parameter.
String.format("{0:dddd, MMMM d, yyyy hh:mm tt}", dt);
Once you are in terminal/command line, access the database/collection you want to use as follows:
show dbs
use <db name>
show collections
choose your collection and type the following to see all contents of that collection:
db.collectionName.find()
More info here on the MongoDB Quick Reference Guide.
Just in case you have a nullable property in your class object:
private static DataTable ConvertToDatatable<T>(List<T> data)
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
table.Columns.Add(prop.Name, prop.PropertyType.GetGenericArguments()[0]);
else
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
Source: CodePath - UI Testing With Espresso
- Finally, we need to pull in the Espresso dependencies and set the test runner in our app build.gradle:
// build.gradle
...
android {
...
defaultConfig {
...
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
}
dependencies {
...
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2') {
// Necessary if your app targets Marshmallow (since Espresso
// hasn't moved to Marshmallow yet)
exclude group: 'com.android.support', module: 'support-annotations'
}
androidTestCompile('com.android.support.test:runner:0.5') {
// Necessary if your app targets Marshmallow (since the test runner
// hasn't moved to Marshmallow yet)
exclude group: 'com.android.support', module: 'support-annotations'
}
}
I've added that to my gradle file and the warning disappeared.
Also, if you get any other dependency listed as conflicting, such as support-annotations, try excluding it too from the androidTestCompile dependencies.
<div :style="{ backgroundImage: `url(${post.image})` }">
there are multiple ways but i found template string easy and simple
To Answer your question: now AWS make cloning real easy see Launch instance from your Existing Instance
This will take the existing instance as a Template for the new once.
or you can also take a snapshot of the existing volume and use the snapshot with the AMI (existing one) which you ping during your instance launch
This is a variation to the answer provided by @Metrics and edited by @Max Ghenis...
l <- sapply(iris, function(x) is.factor(x))
m <- iris[,l]
n <- sapply( m, function(x) { y <- summary(x)/length(x)
len <- length(y[y<0.005 | y>0.995])
cbind(len,t(y))} )
drop_cols_df <- data.frame(var = names(l[l]),
status = ifelse(as.vector(t(n[1,]))==0,"NODROP","DROP" ),
level1 = as.vector(t(n[2,])),
level2 = as.vector(t(n[3,])))
Here, after identifying factor variables, the second sapply
computes what percent of records belong to each level / category of the variable. Then it identifies number of levels over 99.5% or below 0.5% incidence rate (my arbitrary thresholds).
It then goes on to return the number of valid levels and the incidence rate of each level in each categorical variable.
Variables with zero levels crossing the thresholds should not be dropped, while the other should be dropped from the linear model.
The last data frame makes viewing the results easy. It's hard coded for this data set since all factor variables are binomial. This data frame can be made generic easily enough.
require 'pathname'
Pathname.new('/opt/local/bin/ruby').basename
# => #<Pathname:ruby>
I haven't been a Windows user in a long time, but the Pathname rdoc says it has no issues with directory-name separators on Windows.
You're targeting the wrong item with that jQuery selector. The name
of your search bar is searchBar
, not the id
. What you want to use is $('#main_search').val('hi')
.
I tried:
internal static void IndentedNewWSDLString(string filePath)
{
var xml = File.ReadAllText(filePath);
XDocument doc = XDocument.Parse(xml);
File.WriteAllText(filePath, doc.ToString());
}
it is working fine as expected.
This is not possible. Linux permissions and windows permissions do not translate. They are machine specific. It would be a security hole to allow permissions to be set on files before they even arrive on the target system.
I think it would be easier using this CLR Stored procedure SQL-APIConsumer:
exec [dbo].[APICaller_POST]
@URL = 'http://localhost:5000/api/auth/login'
,@BodyJson = '{"Username":"gdiaz","Password":"password"}'
It has multiple procedures that allows you calling API that required a parameters and even passing multiples headers and tokens authentications.
Thanks all. I took bits of each of your solutions and made my own.
The final working solution is:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: '<?php bloginfo('template_url'); ?>/functions/twitter.php',
data: "tweets=<?php echo $ct_tweets; ?>&account=<?php echo $ct_twitter; ?>",
success: function(data) {
$('#twitter-loader').remove();
$('#twitter-container').html(data);
}
});
});
</script>
The "@import" rule could calls in multiple styles files. These files are called by the browser or User Agent when needed e.g. HTML tags call the CSS.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="EN" dir="ltr">
<head>
<title>Using @import</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<style type="text/css">
@import url("main.css");
</style>
</head>
<body>
</body>
</html>
CSS File "main.css" Contains The Following Syntax:
@import url("fineprint.css") print;
@import url("bluish.css") projection, tv;
@import 'custom.css';
@import url("chrome://communicator/skin/");
@import "common.css" screen, projection;
@import url('landscape.css') screen and (orientation:landscape);
To insert in style element use createTexNode don't use innerHTML but:
<script>
var style = document.createElement('style');
style.setAttribute("type", "text/css");
var textNode = document.createTextNode("
@import 'fineprint.css' print;
@import 'bluish.css' projection, tv;
@import 'custom.css';
@import 'chrome://communicator/skin/';
@import 'common.css' screen, projection;
@import 'landscape.css' screen and (orientation:landscape);
");
style.appendChild(textNode);
</script>
Q. List the name of each show, and the number of different times it has been held. List the show which has been held most often first.
event_id show_id event_name judge_id
0101 01 Dressage 01
0102 01 Jumping 02
0103 01 Led in 01
0201 02 Led in 02
0301 03 Led in 01
0401 04 Dressage 04
0501 05 Dressage 01
0502 05 Flag and Pole 02
Ans:
select event_name, count(show_id) as held_times from event
group by event_name
order by count(show_id) desc
I'm assuming you want all three of those as part of the selection criteria. You'll need a few statements in your where but they will be similar to the link your question contained.
SELECT *
FROM MyTable
WHERE [dateColumn] > '3/1/2009' AND [dateColumn] <= DATEADD(day,1,'3/31/2009')
--make it inclusive for a datetime type
AND DATEPART(hh,[dateColumn]) >= 6 AND DATEPART(hh,[dateColumn]) <= 22
-- gets the hour of the day from the datetime
AND DATEPART(dw,[dateColumn]) >= 3 AND DATEPART(dw,[dateColumn]) <= 5
-- gets the day of the week from the datetime
Hope this helps.
High resolution is relative... I was looking at the examples and they mostly cater for milliseconds. However for me it is important to measure microseconds. I have not seen a platform independant solution for microseconds and thought something like the code below will be usefull. I was timing on windows only for the time being and will most likely add a gettimeofday() implementation when doing the same on AIX/Linux.
#ifdef WIN32
#ifndef PERFTIME
#include <windows.h>
#include <winbase.h>
#define PERFTIME_INIT unsigned __int64 freq; QueryPerformanceFrequency((LARGE_INTEGER*)&freq); double timerFrequency = (1.0/freq); unsigned __int64 startTime; unsigned __int64 endTime; double timeDifferenceInMilliseconds;
#define PERFTIME_START QueryPerformanceCounter((LARGE_INTEGER *)&startTime);
#define PERFTIME_END QueryPerformanceCounter((LARGE_INTEGER *)&endTime); timeDifferenceInMilliseconds = ((endTime-startTime) * timerFrequency); printf("Timing %fms\n",timeDifferenceInMilliseconds);
#define PERFTIME(funct) {unsigned __int64 freq; QueryPerformanceFrequency((LARGE_INTEGER*)&freq); double timerFrequency = (1.0/freq); unsigned __int64 startTime; QueryPerformanceCounter((LARGE_INTEGER *)&startTime); unsigned __int64 endTime; funct; QueryPerformanceCounter((LARGE_INTEGER *)&endTime); double timeDifferenceInMilliseconds = ((endTime-startTime) * timerFrequency); printf("Timing %fms\n",timeDifferenceInMilliseconds);}
#endif
#else
//AIX/Linux gettimeofday() implementation here
#endif
Usage:
PERFTIME(ProcessIntenseFunction());
or
PERFTIME_INIT
PERFTIME_START
ProcessIntenseFunction()
PERFTIME_END
Additional to Vasil's answer: If you have the values given as a Scala collection, you can write
val list = List(1,2,3,4,5)
val arr = Array[Int](list:_*)
println(arr.mkString)
But usually the toArray method is more handy:
val list = List(1,2,3,4,5)
val arr = list.toArray
println(arr.mkString)
The previous answer is correct but I'll give you all the code as well.
Your app.config should look like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="ServicesSection" type="RT.Core.Config.ServiceConfigurationSection, RT.Core"/>
</configSections>
<ServicesSection>
<Services>
<add Port="6996" ReportType="File" />
<add Port="7001" ReportType="Other" />
</Services>
</ServicesSection>
</configuration>
Your ServiceConfig
and ServiceCollection
classes remain unchanged.
You need a new class:
public class ServiceConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("Services", IsDefaultCollection = false)]
[ConfigurationCollection(typeof(ServiceCollection),
AddItemName = "add",
ClearItemsName = "clear",
RemoveItemName = "remove")]
public ServiceCollection Services
{
get
{
return (ServiceCollection)base["Services"];
}
}
}
And that should do the trick. To consume it you can use:
ServiceConfigurationSection serviceConfigSection =
ConfigurationManager.GetSection("ServicesSection") as ServiceConfigurationSection;
ServiceConfig serviceConfig = serviceConfigSection.Services[0];
Just simply use this Style
of DataGridRow
:
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
</Style>
</DataGrid.RowStyle>
Yes,that is called short-circuiting.
Please take a look at this wikipedia page on short-circuiting
First create the project from the following link to create larave 7 project: Create Project
Now you need to enter your project folder using the following command:
cd myproject
Now try to run artisan
command, such as, php artisan
.
Or it may happen if you didn't install compose. So if you didn't install composer then run composer install
and try again artisan
command.
Use date format
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse(datetime);
SimpleDateFormat df = new SimpleDateFormat("yyyy");
year = df.format(date);
Add keyword static
to class declaration:
// this is a non-generic static class
public static class LinqHelper
{
}
For Kibana 4 go to this answer
This is easy to do with a terms panel:
If you want to select the count of distinct IP that are in your logs, you should specify in the field clientip
, you should put a big enough number in length (otherwise, it will join different IP under the same group) and specify in the style table. After adding the panel, you will have a table with IP, and the count of that IP:
JD-GUI is a very handy tool for browsing and decompiling JARs
When you json decode , force it to return an array instead of object.
$data = json_decode($json, TRUE); -> // TRUE
This will return an array and you can access the values by giving the keys.
As mentioned, GitHub API returns downloads count of binary file releases. I developed a little script to easly get downloads count by command line.
You could use the static StartupPath property of the Application class.
For Tomcat v8.5.4 and above, the file <tomcat>/webapps/manager/META-INF/context.xml
has been adjusted:
<Context antiResourceLocking="false" privileged="true" >
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
</Context>
Change this file to comment the Valve
:
<Context antiResourceLocking="false" privileged="true" >
<!--
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
-->
</Context>
After that, refresh your browser (not need to restart Tomcat), you can see the manager page.
I'm not sure if there is pre-made library for this, but if you're willing to get your hands dirty with a little Perl, you could likely do something with Text::CSV
and HTML::Parser
.
Just add a .
to it:
svn checkout file:///home/landonwinters/svn/waterproject/trunk .
That means: check out to current directory.
I created this little function that replaces string on string (case-sensitive) with limit, without the need of Regexp. It works fine.
function str_replace_limit($search, $replace, $string, $limit = 1) {
$pos = strpos($string, $search);
if ($pos === false) {
return $string;
}
$searchLen = strlen($search);
for ($i = 0; $i < $limit; $i++) {
$string = substr_replace($string, $replace, $pos, $searchLen);
$pos = strpos($string, $search);
if ($pos === false) {
break;
}
}
return $string;
}
Example usage:
$search = 'foo';
$replace = 'bar';
$string = 'foo wizard makes foo brew for evil foo and jack';
$limit = 2;
$replaced = str_replace_limit($search, $replace, $string, $limit);
echo $replaced;
// bar wizard makes bar brew for evil foo and jack
Isn't simply android:saveEnabled="true"
in the ListView xml declaration enough?
The session is a server side thing, you cannot access it using jQuery.
You can write an Http handler (that will share the sessionid if any) and return the value from there using $.ajax
.
use:
opener.document.<id of document>.innerHTML = xmlhttp.responseText;
It worked for me:
window.location = $('#myanchor').attr('href');
Strings can have for loops to:
for a in string:
print a
I came to this site looking for an easy way to copy without changing cell references. But now I thnk my own workaround is simpler than most of these methods. My method relies on the fact that Copy changes references but Move doesn't. Here's a simple example.
Assume you have raw data in columns A and B, and a formula in C (e.g. C=A+B) and you want the same formula in column F but Copying from C to F leads to F=D+E.
I've done this with a range of cells so I imagine it would work with virtually any level of complexity. You just need an empty area to park the coiped cells. And of course you have to remember where you left them.
#FFFFEEE
is not a correct color code. Try with #FFFFEE
instead.
With Ctrl + Shift + L you can open the "key assist", where you can find all the shortcuts.
Hibernate is a JPA implementation, while Spring Data JPA is a JPA data access abstraction. Spring Data JPA cannot work without a JPA provider.
Spring Data offers a solution to the DDD Repository
pattern or the legacy GenericDao
custom implementations. It can also generate JPA queries on your behalf through method name conventions.
With Spring Data, you may use Hibernate, EclipseLink, or any other JPA provider. A very interesting benefit of using Spring or Java EE is that you can control transaction boundaries declaratively using the @Transactional
annotation.
Spring JDBC is much more lightweight, and it's intended for native querying, and if you only intend to use JDBC alone, then you are better off using Spring JDBC to deal with the JDBC verbosity.
Therefore, Hibernate and Spring Data are complementary rather than competitors.
You can try export http_proxy=http://your_proxy:your_port
With PHP I'm doing:
<a href="?action=logout">logout.</a>
if(isset($_GET['action']) && $_GET['action'] === 'logout'){
$facebook->destroySession();
header(WHERE YOU WANT TO REDIRECT TO);
exit();
}
Works and is nice and easy am just trying to find a logout button graphic now!
typedef struct{
char array[4];
}my_array;
my_array array = { .array = {1,1,1,1} }; // initialisation
void assign(my_array a)
{
array.array[0] = a.array[0];
array.array[1] = a.array[1];
array.array[2] = a.array[2];
array.array[3] = a.array[3];
}
char num = 5;
char ber = 6;
int main(void)
{
printf("%d\n", array.array[0]);
// ...
// this works even after initialisation
assign((my_array){ .array = {num,ber,num,ber} });
printf("%d\n", array.array[0]);
// ....
return 0;
}
The filesystem size can be different from the patition size. To repair you need to do this
df -h
see what is the name of the partition say /dev/sda3
resize2fs /dev/sda3
I came here because I'm new with python and lazy so I was searching an example to create a list of 2 lists, after a while a realized the topic here could be wrong... this is a code to create a list of lists:
listoflists = []
for i in range(0,2):
sublist = []
for j in range(0,10)
sublist.append((i,j))
listoflists.append(sublist)
print listoflists
this the output [ [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9)], [(1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9)] ]
The problem with your code seems to be you are creating a tuple with your list and you get the reference to the list instead of a copy. That I guess should fall under a tuple topic...
To expand upon nosklo's explanation:
a = {}
b = ['some', 'list']
a[b] = 'some' # this won't work
a[tuple(b)] = 'some' # this will, same as a['some', 'list']
You are getting Floating point exception because Number % i
, when i
is 0
:
int Is_Prime( int Number ){
int i ;
for( i = 0 ; i < Number / 2 ; i++ ){
if( Number % i != 0 ) return -1 ;
}
return Number ;
}
Just start the loop at i = 2
. Since i = 1
in Number % i
it always be equal to zero, since Number is a int.
As of ASP.NET MVC 5.1, adding a class to an EditorFor
is possible (the original question specified ASP.NET MVC 3, and the accepted answer is still the best with that considered).
@Html.EditorFor(x=> x.MyProperty,
new { htmlAttributes = new { @class = "MyCssClass" } })
See: What's New in ASP.NET MVC 5.1, Bootstrap support for editor templates
The best way is to simply reset the password by connecting with a domain/local admin (so you may need help from your system administrators), but this only works if SQL Server was set up to allow local admins (these are now left off the default admin group during setup).
If you can't use this or other existing methods to recover / reset the SA password, some of which are explained here:
Then you could always backup your important databases, uninstall SQL Server, and install a fresh instance.
You can also search for less scrupulous ways to do it (e.g. there are password crackers that I am not enthusiastic about sharing).
As an aside, the login properties for sa
would never say Windows Authentication. This is by design as this is a SQL Authentication account. This does not mean that Windows Authentication is disabled at the instance level (in fact it is not possible to do so), it just doesn't apply for a SQL auth account.
I wrote a tip on using PSExec to connect to an instance using the NT AUTHORITY\SYSTEM
account (which works < SQL Server 2012), and a follow-up that shows how to hack the SqlWriter service (which can work on more modern versions):
And some other resources:
The problem is, os.path.join
doesn't take a list
as argument, it has to be separate arguments.
This is where *
, the 'splat' operator comes into play...
I can do
>>> s = "c:/,home,foo,bar,some.txt".split(",")
>>> os.path.join(*s)
'c:/home\\foo\\bar\\some.txt'
I have been looking into the same problem! I think your problem is related to where you identify the variable that you use to populate the ArrayList that you return. If you define it inside the loop, then it will always reference the last row in the table in the database. In order to avoid this, you have to identify it outside the loop:
String name;
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
name = cursor.getString(cursor
.getColumnIndex(countyname));
list.add(name);
cursor.moveToNext();
}
}
SELECT * FROM NOTES ORDER BY UPPER(title)
You can use window.scrollTo()
, like this:
window.scrollTo(0, 0); // values are x,y-offset
You should use the following code :
Class2 cls2 = new Class2();
cls2.UpdateEmployee();
In case you don't want to create a new instance to call the method, you can decalre the method as static
and then you can just call Class2.UpdateEmployee()
.
As +Volatility and yourself pointed out, sets are unordered. If you need the elements to be in order, just call sorted
on the set:
>>> y = [1, 1, 6, 6, 6, 6, 6, 8, 8]
>>> sorted(set(y))
[1, 6, 8]
This problem is "best" solved by using an anonymous function to pass-in the jQuery object thusly:
The Anonymous Function Looks Like:
<script type="text/javascript">
(function($) {
// You pass-in jQuery and then alias it with the $-sign
// So your internal code doesn't change
})(jQuery);
</script>
This is JavaScript's method of implementing (poor man's) 'Dependency Injection' when used alongside things like the 'Module Pattern'.
So Your Code Would Look Like:
Of course, you might want to make some changes to your internal code now, but you get the idea.
<script type="text/javascript">
(function($) {
$.fn.pluginbutton = function(options) {
myoptions = $.extend({ left: true });
return this.each(function() {
var focus = false;
if (focus === false) {
this.hover(function() {
this.animate({ backgroundPosition: "0 -30px" }, { duration: 0 });
this.removeClass('VBfocus').addClass('VBHover');
}, function() {
this.animate({ backgroundPosition: "0 0" }, { duration: 0 });
this.removeClass('VBfocus').removeClass('VBHover');
});
}
this.mousedown(function() {
focus = true
this.animate({ backgroundPosition: "0 30px" }, { duration: 0 });
this.addClass('VBfocus').removeClass('VBHover');
}, function() {
focus = false;
this.animate({ backgroundPosition: "0 0" }, { duration: 0 });
this.removeClass('VBfocus').addClass('VBHover');
});
});
}
})(jQuery);
</script>
Wouldn't you be better off with
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl="CMS_1.aspx"
Target="_blank">
Click here
</asp:HyperLink>
Because, to replicate your desired behavior on an asp:Button
, you have to call window.open
on the OnClientClick
event of the button which looks a lot less cleaner than the above solution. Plus asp:HyperLink
is there to handle scenarios like this.
If you want to replicate this using an asp:Button
, do this.
<asp:Button ID="btn" runat="Server"
Text="SUBMIT"
OnClientClick="javascript:return openRequestedPopup();"/>
JavaScript function.
var windowObjectReference;
function openRequestedPopup() {
windowObjectReference = window.open("CMS_1.aspx",
"DescriptiveWindowName",
"menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes");
}
HTML Markup :
<div class="form-group">
<input id="rdMale" type="radio" class="clsGender" value="Male" name="rdGender" /> Male
<input id="rdFemale" type="radio" class="clsGender" value="Female" name="rdGender" /> Female
</div>
Get selected value by radio button Id:
$("input[name='rdGender']").click(function () {
alert($("#rdMale").val());
});
Get value by radiobutton Classname
$(".clsGender").click(function () {
alert($(this).val());
//or
alert($(".clsGender:checked").val());
});
Get value by name
$("input[name='rdGender']").click(function () {
var rdVaule = $("input[name='rdGender']:checked").val();
alert(rdVaule);
});
instead of doing pure jquery, i would do:
$(".mytext").mouseover(function() {
x= $(this).position().left - document.scrollLeft
y= $(this).position().top - document.scrollTop
$("#dialog").dialog('option', 'position', [y, x]);
}
if i am understanding your question correctly, the code you have is positioning the dialog as if the page had no scroll, but you want it to take the scroll into account. my code should do that.
The flags, or parameters that you can use with IFRAME and OBJECT embeds are documented here; the details about which parameter works with what player are also clearly mentioned:
YouTube Embedded Players and Player Parameters
You will notice that autoplay
is supported by all players (AS3, AS2 and HTML5).
I had this same problem when using a key of 4096 bits:
$ ssh-keygen -t rsa -C "GitLab" -b 4096
$ ssh -vT git@gitlabhost
...
debug1: Offering public key: /home/user/.ssh/id_rsa
debug1: Authentications that can continue: publickey,password
debug1: Trying private key: /home/user/.ssh/id_dsa
debug1: Trying private key: /home/user/.ssh/id_ecdsa
debug1: Next authentication method: password
git@gitlabhost's password:
Connection closed by host
But with the 2048 bit key (the default size), ssh connects to gitlab without prompting for a password (after adding the new pub key to the user's gitlab ssh keys)
$ ssh-keygen -t rsa -C "GitLab"
$ ssh -vT git@gitlabhost
Welcome to GitLab, Joe User!
You can also name your foreign key constraint by using:
CONSTRAINT your_name_here FOREIGN KEY (question_exam_id) REFERENCES EXAMS (exam_id)
For oracle:
select(
select count(*) from foo1 where ID = '00123244552000258'
+
select count(*) from foo2 where ID = '00123244552000258'
+
select count(*) from foo3 where ID = '00123244552000258'
) total from dual;
I'm getting the same error on Mac OS X 10.11.6:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
After a lot of agonizing and digging through advice here and in related questions, none of which seemed to fix the problem, I went back and deleted the installed folders, and just did brew install mysql
.
Still getting the same error with most commands, but this works:
/usr/local/bin/mysqld
and returns:
/usr/local/bin/mysqld: ready for connections.
Version: '5.7.12' socket: '/tmp/mysql.sock' port: 3306 Homebrew
Full Example (Python 3):
For Python 2.x look into Note below
import re
mylist = ["dog", "cat", "wildcat", "thundercat", "cow", "hooo"]
r = re.compile(".*cat")
newlist = list(filter(r.match, mylist)) # Read Note
print(newlist)
Prints:
['cat', 'wildcat', 'thundercat']
Note:
For Python 2.x developers, filter
returns a list already. In Python 3.x filter
was changed to return an iterator so it has to be converted to list
(in order to see it printed out nicely).
In my case I also have unmanaged dll's (C++) in workspace and if you specify:
<files>
<file src="bin\*.dll" target="lib" />
</files>
nuget would try to load every dll as an assembly, even the C++ libraries! To avoid this
behaviour explicitly define your C# assemblies with references
tag:
<references>
<reference file="Managed1.dll" />
<reference file="Managed2.dll" />
</references>
Remark: parent of references is metadata -> according to documentation https://docs.microsoft.com/en-us/nuget/reference/nuspec#general-form-and-schema
Documentation: https://docs.microsoft.com/en-us/nuget/reference/nuspec
This one worked for me, in startup.bat
the following line needs to be added if it doesn't exist set JAVA_OPTS
with the value -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256
. The full line:
set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256
There is no CSS property like background-opacity that you can use only for changing the opacity or transparency of an element's background without affecting the child elements, on the other hand if you will try to use the CSS opacity property it will not only changes the opacity of background but changes the opacity of all the child elements as well. In such situation you can use RGBA color introduced in CSS3 that includes alpha transparency as part of the color value. Using RGBA color you can set the color of the background as well as its transparency.
You should use the for
command, here is an example:
@echo off
rem Commands go here
exit /b
:output
for /f "tokens=* useback" %%a in (`%~1`) do set "output=%%a"
and you can use call :output "Command goes here"
then the output will be in the %output%
variable.
Note: If you have a command output that is multiline, this tool will set
the output to the last line of your multiline command.
Spring won't allow to decouple via java.util.Properties
from Spring Environment.
But Properties.load()
still works in a Spring boot application:
Properties p = new Properties();
try (InputStream is = getClass().getResourceAsStream("/my.properties")) {
p.load(is);
}
To go back without refreshing the page, We can do in html like below javascript:history.back()
<a class="btn btn-danger" href="javascript:history.back()">Go Back</a>
By default the route configuration follows RESTFul conventions meaning that it will accept only the Get, Post, Put and Delete action names (look at the route in global.asax => by default it doesn't allow you to specify any action name => it uses the HTTP verb to dispatch). So when you send a GET request to /api/users/authenticate
you are basically calling the Get(int id)
action and passing id=authenticate
which obviously crashes because your Get action expects an integer.
If you want to have different action names than the standard ones you could modify your route definition in global.asax
:
Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { action = "get", id = RouteParameter.Optional }
);
Now you can navigate to /api/users/getauthenticate
to authenticate the user.
Update 2019 - Bootstrap 4.0.0
The pull-right
class is now float-right
in Bootstrap 4...
<div class="row">
<div class="col-12">One <input type="button" class="btn float-right" value="test"></div>
<div class="col-12">Two <input type="button" class="btn float-right" value="test"></div>
</div>
http://www.codeply.com/go/nTobetXAwb
It's also better to not align the ul list and use block elements for the rows.
Is float-right
still not working?
Remember that Bootstrap 4 is now flexbox, and many elements are display:flex
which can prevent float-right from working. In some cases, the util classes like align-self-end
or ml-auto
work to right align elements that are inside a flexbox container like a Bootstrap 4 .row, Card or Nav.
Also remember that text-right
still works on inline elements.
Bootstrap 4 align right examples
Bootstrap 3
Use the pull-right
class.
USB 5v power is always on (even when the computer is turned off, on some computers and on some ports.) You will probably need to program an Arduino with some sort of switch, and control it via Serial library from USB plugged in to the computer.
In other words, a combination of this switch tutorial and this tutorial on communicating via Serial libary to Arduino plugged in via USB.
echo "US/Central - 10:26 PM (CST)" | sed -n "s/^.*-\s*\(\S*\).*$/\1/p"
-n suppress printing
s substitute
^.* anything at the beginning
- up until the dash
\s* any space characters (any whitespace character)
\( start capture group
\S* any non-space characters
\) end capture group
.*$ anything at the end
\1 substitute 1st capture group for everything on line
p print it
console.log('Hello, \n' +
'Text under your Header\n' +
'-------------------------\n' +
'More Text\n' +
'Moree Text\n' +
'Moooooer Text\n' );
This works great for me for text only, and easy on the eye.
Actually I wanted same alike thing, To get one year backward date, for a given date! :-)
With the hint of above answer from @mohammad mohsenipur I got to the following link, via his given link!
Luckily, there is a method same as date_add method, named date_sub method! :-) I do the following to get done what I wanted!
$date = date_create('2000-01-01');
date_sub($date, date_interval_create_from_date_string('1 years'));
echo date_format($date, 'Y-m-d');
Hopes this answer will help somebody too! :-)
Good luck guys!
Inside template this working finely.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="">
<input ng-model="name" value="0">
<p>My first expression: {{ (name-0) + 5 }}</p>
</div>
</body>
</html>
I'd like to add something that hasn't been pointed out. Java doesn't take into account the values you have given the variables (2 and 3) in...
short a = 2; short b = 3; short c = a + b;
So as far as Java knows, you could done this...
short a = 32767; short b = 32767; short c = a + b;
Which would be outside the range of short, it autoboxes the result to an int becuase it's "possible" that the result will be more than a short but not more than an int. Int was chosen as a "default" because basically most people wont be hard coding values above 2,147,483,647 or below -2,147,483,648
I think you are forgetting about the border. Having a one-pixel-wide border on the Div will take away two pixels of total length. Therefore it will appear as though the div is two pixels shorter than it actually is.
Not tested but should work
products.sort((a,b)=>a.title.rendered > b.title.rendered)
You just need to do:
#!/bin/bash
count=$(cat last_queries.txt | wc -l)
$(perl test.pl test2 $count)
However, if you want to call your Perl command later, and that's why you want to assign it to a variable, then:
#!/bin/bash
count=$(cat last_queries.txt | wc -l)
var="perl test.pl test2 $count" # You need double quotes to get your $count value substituted.
...stuff...
eval $var
As per Bash's help:
~$ help eval
eval: eval [arg ...]
Execute arguments as a shell command.
Combine ARGs into a single string, use the result as input to the shell,
and execute the resulting commands.
Exit Status:
Returns exit status of command or success if command is null.
From here download this video so we have the same video file for the test. Make sure to have that mp4 file in the same directory of your python code. Then also make sure to run the python interpreter from the same directory.
Then modify the code, ditch waitKey
that's wasting time also without a window it cannot capture the keyboard events. Also we print the success
value to make sure it's reading the frames successfully.
import cv2
vidcap = cv2.VideoCapture('big_buck_bunny_720p_5mb.mp4')
success,image = vidcap.read()
count = 0
while success:
cv2.imwrite("frame%d.jpg" % count, image) # save frame as JPEG file
success,image = vidcap.read()
print('Read a new frame: ', success)
count += 1
How does that go?
Kotlin version would be
fun getHeaderInterceptor():Interceptor{
return object : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val request =
chain.request().newBuilder()
.header(Headers.KEY_AUTHORIZATION, "Bearer.....")
.build()
return chain.proceed(request)
}
}
}
private fun createOkHttpClient(): OkHttpClient {
return OkHttpClient.Builder()
.apply {
if(BuildConfig.DEBUG){
this.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC))
}
}
.addInterceptor(getHeaderInterceptor())
.build()
}
Since these all are wonderful infos there's a little api called Mandrill to send mails from javascript and it works perfectly. You can give it a shot. Here's a little tutorial for the start.
Change this line:
cmd.CommandText = "INSERT INTO Data (Name,PhoneNo,Address) VALUES (" + txtName.Text + "," + txtPhone.Text + "," + txtAddress.Text + ");";
to this:
cmd.CommandText = "INSERT INTO Data (Name,PhoneNo,Address) VALUES ('" + txtName.Text + "','" + txtPhone.Text + "','" + txtAddress.Text + "');";
Your insert command is expecting text, and you need single quotes (') between the actual value so SQL can understand it as text.
EDIT: For those of you who aren't happy with this answer, I would like to point out that there is an issue with this code in regards to SQL Injection. When I answered this question I only considered the question in point which was the missing single-quote on his code and I pointed out how to fix it. A much better answer has been posted by Adam (and I voted for it), where he explains the issues with injection and shows a way to prevent. Now relax and be happy guys.
React 16.3 added a new convenient way to handle this by creating a ref in component's constructor and use it like below:
class MyForm extends Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
componentDidMount() {
this.textInput.current.focus();
}
render() {
return(
<div>
<input ref={this.textInput} />
</div>
);
}
}
For more details about React.createRef
, you can check this article in React blog.
Update:
Starting from React 16.8, useRef
hook can be used in function components to achieve the same result:
import React, { useEffect, useRef } from 'react';
const MyForm = () => {
const textInput = useRef(null);
useEffect(() => {
textInput.current.focus();
}, []);
return (
<div>
<input ref={textInput} />
</div>
);
};
Take a look at jQuery's .load() http://api.jquery.com/load-event/
$('script').load(function () { });
I made my own way based on Caitlin Morris's answer for fetching all folowers and followings on Instagram. Just copy this code, paste in browser console and wait for a few seconds.
You need to use browser console from instagram.com tab to make it works.
let username = 'USERNAME'
let followers = [], followings = []
try {
let res = await fetch(`https://www.instagram.com/${username}/?__a=1`)
res = await res.json()
let userId = res.graphql.user.id
let after = null, has_next = true
while (has_next) {
await fetch(`https://www.instagram.com/graphql/query/?query_hash=c76146de99bb02f6415203be841dd25a&variables=` + encodeURIComponent(JSON.stringify({
id: userId,
include_reel: true,
fetch_mutual: true,
first: 50,
after: after
}))).then(res => res.json()).then(res => {
has_next = res.data.user.edge_followed_by.page_info.has_next_page
after = res.data.user.edge_followed_by.page_info.end_cursor
followers = followers.concat(res.data.user.edge_followed_by.edges.map(({node}) => {
return {
username: node.username,
full_name: node.full_name
}
}))
})
}
console.log('Followers', followers)
has_next = true
after = null
while (has_next) {
await fetch(`https://www.instagram.com/graphql/query/?query_hash=d04b0a864b4b54837c0d870b0e77e076&variables=` + encodeURIComponent(JSON.stringify({
id: userId,
include_reel: true,
fetch_mutual: true,
first: 50,
after: after
}))).then(res => res.json()).then(res => {
has_next = res.data.user.edge_follow.page_info.has_next_page
after = res.data.user.edge_follow.page_info.end_cursor
followings = followings.concat(res.data.user.edge_follow.edges.map(({node}) => {
return {
username: node.username,
full_name: node.full_name
}
}))
})
}
console.log('Followings', followings)
} catch (err) {
console.log('Invalid username')
}
Decimal representation of floating point numbers is kind of strange. If you have a number with 15 decimal places and convert that to a double
, then print it out with exactly 15 decimal places, you should get the same number. On the other hand, if you print out an arbitrary double
with 15 decimal places and the convert it back to a double
, you won't necessarily get the same value back—you need 17 decimal places for that. And neither 15 nor 17 decimal places are enough to accurately display the exact decimal equivalent of an arbitrary double
. In general, you need over 100 decimal places to do that precisely.
See the Wikipedia page for double-precision and this article on floating-point precision.
The easiest way to fix this is to add a new factor to your column. Use the levels function to determine how many factors you have and then add a new factor.
> levels(data$Fireplace.Qu)
[1] "Ex" "Fa" "Gd" "Po" "TA"
> levels(data$Fireplace.Qu) = c("Ex", "Fa", "Gd", "Po", "TA", "None")
[1] "Ex" "Fa" "Gd" "Po" " TA" "None"
My Experience with this issue using WPF C# coping to clipboard and System.Threading.ThreadStateException
is here with my code that worked correctly with all browsers:
Thread thread = new Thread(() => Clipboard.SetText("String to be copied to clipboard"));
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start();
thread.Join();
credits to this post here
But this works only on localhost, so don't try this on a server, as it's not going to work.
On server-side, I did it by using zeroclipboard
. The only way, after a lot of research.
The relevant part of C11 standard draft n1570 6.7.9 initialization says:
14 An array of character type may be initialized by a character string literal or UTF-8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.
and
21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
Thus, the '\0' is appended, if there is enough space, and the remaining characters are initialized with the value that a static char c;
would be initialized within a function.
Finally,
10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:
[--]
- if it has arithmetic type, it is initialized to (positive or unsigned) zero;
[--]
Thus, char
being an arithmetic type the remainder of the array is also guaranteed to be initialized with zeroes.
Edit: use
<=
or>=
to count today's date.
This is the right answer for your code. Just use the strtotime() php function.
$paymentDate = date('Y-m-d');
$paymentDate=date('Y-m-d', strtotime($paymentDate));
//echo $paymentDate; // echos today!
$contractDateBegin = date('Y-m-d', strtotime("01/01/2001"));
$contractDateEnd = date('Y-m-d', strtotime("01/01/2012"));
if (($paymentDate >= $contractDateBegin) && ($paymentDate <= $contractDateEnd)){
echo "is between";
}else{
echo "NO GO!";
}
Heres my code for a fade in/out toggle functions.
fadeIn: function (len) {
var obj = this.e;
obj.style.display = '';
var op = 0;
var timer = setInterval(function () {
if (op >= 1 || op >= 1.0){
console.log('done', op)
clearInterval(timer);
}
obj.style.opacity = op.toFixed(1);
op += 0.1;
console.log(obj.style.opacity);
}, len);
return this;
},
fadeOut: function (len) {
var obj = this.e;
var op = 1;
var timer = setInterval(function () {
if (op <= 0){
clearInterval(timer);
console.log('done', op)
obj.style.display = 'none';
}
obj.style.opacity = op.toFixed(1);
op -= 0.1;
console.log(obj.style.opacity)
}, len);
return this;
},
This was from a jQuery style lib i did. hope it's helpfull. link to lib on cloud9: https://c9.io/christopherdumas/magik_wb
To me it was a wrong deployment. Deployed properly, everything works (check my question for details).
The solution for me was very simple (after 10 hours of searching). Above where your folders are there is a combobox that says "android" click it and choose "Project".
Starting from Xcode 8, you can use the class property attribute as answered by Berbie.
However, in the implementation, you need to define both class getter and setter for the class property using a static variable in lieu of an iVar.
Sample.h
@interface Sample: NSObject
@property (class, retain) Sample *sharedSample;
@end
Sample.m
@implementation Sample
static Sample *_sharedSample;
+ ( Sample *)sharedSample {
if (_sharedSample==nil) {
[Sample setSharedSample:_sharedSample];
}
return _sharedSample;
}
+ (void)setSharedSample:(Sample *)sample {
_sharedSample = [[Sample alloc]init];
}
@end
I am using CDN for my project and as part of fallback handling, i was using below code,
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
if ((typeof jQuery == 'undefined')) {
document.write(unescape("%3Cscript src='/Responsive/Scripts/jquery-1.9.1.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>
Just to verify, i removed CDN reference and execute the code. Its broken and it's never entered into if loop as typeof jQuery is coming as function instead of undefined .
This is because of cached older version of jquery 1.6.1 which return function and break my code because i am using jquery 1.9.1. As i need exact version of jquery, i modified code as below,
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
if ((typeof jQuery == 'undefined') || (jQuery.fn.jquery != "1.9.1")) {
document.write(unescape("%3Cscript src='/Responsive/Scripts/jquery-1.9.1.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>
You could encode the binary data using base64 and put it into a Base64 element; the below article is a pretty good one on the subject.
You don't see anything, because of buffering. The output is shown, when there are enough lines or end of file is reached. tail -f
means wait for more input, but there are no more lines in file
and so the pipe to grep
is never closed.
If you omit -f
from tail
the output is shown immediately:
tail file | grep A1 | awk '{print $NF}'
@EdMorton is right of course. Awk can search for A1
as well, which shortens the command line to
tail file | awk '/A1/ {print $NF}'
or without tail, showing the last column of all lines containing A1
awk '/A1/ {print $NF}' file
Thanks to @MitchellTracy's comment, tail
might miss the record containing A1
and thus you get no output at all. This may be solved by switching tail
and awk
, searching first through the file and only then show the last line:
awk '/A1/ {print $NF}' file | tail -n1
By default, a comma is used as a delimiter in a CSV file. However, some CSV files can use delimiters other than a comma. Few popular ones are |
and \t
.
import csv
data_list = [["SN", "Name", "Contribution"],
[1, "Linus Torvalds", "Linux Kernel"],
[2, "Tim Berners-Lee", "World Wide Web"],
[3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
writer = csv.writer(file, delimiter='|')
writer.writerows(data_list)
output:
SN|Name|Contribution
1|Linus Torvalds|Linux Kernel
2|Tim Berners-Lee|World Wide Web
3|Guido van Rossum|Python Programming
import csv
row_list = [["SN", "Name", "Contribution"],
[1, "Linus Torvalds", "Linux Kernel"],
[2, "Tim Berners-Lee", "World Wide Web"],
[3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC, delimiter=';')
writer.writerows(row_list)
output:
"SN";"Name";"Contribution"
1;"Linus Torvalds";"Linux Kernel"
2;"Tim Berners-Lee";"World Wide Web"
3;"Guido van Rossum";"Python Programming"
As you can see, we have passed csv.QUOTE_NONNUMERIC
to the quoting
parameter. It is a constant defined by the csv
module.
csv.QUOTE_NONNUMERIC
specifies the writer
object that quotes should be added around the non-numeric entries.
There are 3 other predefined constants you can pass to the quoting
parameter:
csv.QUOTE_ALL
- Specifies the writer
object to write CSV file with quotes around all the entries.csv.QUOTE_MINIMAL
- Specifies the writer
object to only quote those fields which contain special characters (delimiter, quotechar or any characters in lineterminator)csv.QUOTE_NONE
- Specifies the writer
object that none of the entries should be quoted. It is the default value.import csv
row_list = [["SN", "Name", "Contribution"],
[1, "Linus Torvalds", "Linux Kernel"],
[2, "Tim Berners-Lee", "World Wide Web"],
[3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC,
delimiter=';', quotechar='*')
writer.writerows(row_list)
output:
*SN*;*Name*;*Contribution*
1;*Linus Torvalds*;*Linux Kernel*
2;*Tim Berners-Lee*;*World Wide Web*
3;*Guido van Rossum*;*Python Programming*
Here, we can see that quotechar='*'
parameter instructs the writer
object to use *
as quote for all non-numeric values.
Simple way to detect scroll up/down on android listview
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount){
if(prevVisibleItem != firstVisibleItem){
if(prevVisibleItem < firstVisibleItem)
//ScrollDown
else
//ScrollUp
prevVisibleItem = firstVisibleItem;
}
dont forget
yourListView.setOnScrollListener(yourScrollListener);
This is the way to iterate on this array:
foreach($hotels as $row) {
foreach($row['rooms'] as $k) {
echo $k['boards']['board_id'];
echo $k['boards']['price'];
}
}
You want to iterate on the hotels and the rooms (the ones with numeric indexes), because those seem to be the "collections" in this case. The other arrays only hold and group properties.
android.os.NetworkOnMainThreadException
occurs when you try to access network on your main thread (You main activity execution). To avoid this, you must create a separate thread or AsyncTask
or Runnable
implementation to execute your JSON data loading. Since HoneyComb you can not further execute the network task on main thread.
Here is the implementation using AsyncTask
for a network task execution
If you are using parallelMap
you'll need to export custom functions to the slave jobs, otherwise you get an error "could not find function ".
If you set a non-missing level on parallelStart
the same argument should be passed to parallelExport
, else you get the same error. So this should be strictly followed:
parallelStart(mode = "<your mode here>", N, level = "<task.level>")
parallelExport("<myfun>", level = "<task.level>")
You can use a very good online tool for it. Here is the link dreampuf.github.io Just replace the code inside editer with your code.
I like and used the above solution or a system wide search and replace among thousands of files:
find -name '*.htm?' -print -exec sed -i.bak 's/foo/bar/g' {} \;
I assume with the '*.htm?' instead of .html it searches and finds .htm and .html files alike.
I replace the .bak with the more system wide used tilde (~) to make clean up of backup files easier.
I think the easiest workaround would be to use 'select' with 'multiple' specified:
<select ng-model="selectedfruit" multiple ng-options="v for v in fruit"></select>
Otherwise, I think you'll have to process the list to construct the list
(by $watch()
ing the model array bind with checkboxes).
I was facing same issue, for me adding certificate to trust store solved this issue.
My functional approach. its capstilise first character in sentence after whitescape in whole paragraph.
For capatilising only first character of the word just remove .split(" ")
b.name.split(" ")
.filter { !it.isEmpty() }
.map { it.substring(0, 1).toUpperCase()
+it.substring(1).toLowerCase() }
.joinToString(" ")
You are using the wrong type. The Array(...)
function returns a Variant
, not a String
.
Thus, in the Declaration section of your module (it does not need to be a different module!), you define
Public colHeader As Variant
and somewhere at the beginning of your program code (for example, in the Workbook_Open
event) you initialize it with
colHeader = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")
Another (simple) alternative would be to create a function that returns the array, e.g. something like
Public Function GetHeaders() As Variant
GetHeaders = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")
End Function
This has the advantage that you do not need to initialize the global variable and the drawback that the array is created again on every function call.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//hide status bar
requestWindowFeature( Window.FEATURE_NO_TITLE );
getWindow().setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN );
setContentView(R.layout.activity_main);
}
According to Google's Machine Learning Glossary, an epoch is defined as
"A full training pass over the entire dataset such that each example has been seen once. Thus, an epoch represents N/batch_size
training iterations, where N is the total number of examples."
If you are training model for 10 epochs with batch size 6, given total 12 samples that means:
the model will be able to see whole dataset in 2 iterations ( 12 / 6 = 2) i.e. single epoch.
overall, the model will have 2 X 10 = 20 iterations (iterations-per-epoch X no-of-epochs)
re-evaluation of loss and model parameters will be performed after each iteration!
Look for "poi-3.17.jar"!!!
Problem solved and errors disappeared.
You can do this very easily in Android Studio.
Create a libraries
folder underneath your project main directory. For example, if your project is OpenCVExamples
, you would create a OpenCVExamples/libraries
folder.
Go to the location where you have SDK "\OpenCV-2.4.8-android-sdk\sdk" here you will find the java
folder, rename it to opencv
.
Now copy the complete opencv directory from the SDK into the libraries folder you just created.
Now create a build.gradle
file in the opencv
directory with the following contents
apply plugin: 'android-library'
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.9.+'
}
}
android {
compileSdkVersion 19
buildToolsVersion "19.0.1"
defaultConfig {
minSdkVersion 8
targetSdkVersion 19
versionCode 2480
versionName "2.4.8"
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
res.srcDirs = ['res']
aidl.srcDirs = ['src']
}
}
}
Edit your settings.gradle file in your application’s main directory and add this line:
include ':libraries:opencv'
Sync your project with Gradle and it should looks like this
Right click on your project then click on the Open Module Settings
then Choose Modules from the left-hand list, click on your application’s module, click on the Dependencies tab, and click on the + button to add a new module dependency.
Choose Module dependency
. It will open a dialog with a list of modules to choose from; select “:libraries:opencv”.
Create a jniLibs
folder in the /app/src/main/
location and copy the all the folder with *.so files (armeabi, armeabi-v7a, mips, x86) in the jniLibs
from the OpenCV SDK.
Click OK. Now everything done, go and enjoy with OpenCV.
CTRL+N-- to open a new document.
Right Edge find "MORE SHAPES" then "SOFTWARES AND DATABASES" and finaly "SOFTWARES". All UML DIAGRAMS are available here.
For me, the menu item Inspect Devices wasn't available (not shown at all). But, simply browsing to chrome://inspect/#devices showed me my device and I was able to use the port forward etc. I have no idea why the menu item is not displayed.
Phone: Android Galaxy S4
OS: Mac OS X
Try this. I am using Jupyter notebook (OS: Ubuntu 16.04 LTS on Google Cloud Platform + on Windows). Executed following command in the Jupyter notebook to install opencv:
!pip install opencv-contrib-python #working on both Windows and Ubuntu
After successful installation you will get following message:
Successfully installed opencv-contrib-python-4.1.0.25
Now restart the kernel and try to import opencv as:
import cv2
The same command can be used to installed opencv on Windows as well.
SOLUTION 2: try following commands to install opencv: For Ubuntu: Run following command from terminal:
sudo apt-get install libsm6 libxrender1 libfontconfig1
Restart Jupyter notebook kernel and execute following command:
!pip install opencv-contrib-python
NOTE: You can run all the above commands from the terminal as well without using '!'.
I think the importance of the concept "Turing Complete" is in the the ability to identify a computing machine (not necessarily a mechanical/electrical "computer") that can have its processes be deconstructed into "simple" instructions, composed of simpler and simpler instructions, that a Universal machine could interpret and then execute.
I highly recommend The Annotated Turing
@Mark i think what you are explaining is a mix between the description of the Universal Turing Machine and Turing Complete.
Something that is Turing Complete, in a practical sense, would be a machine/process/computation able to be written and represented as a program, to be executed by a Universal Machine (a desktop computer). Though it doesn't take consideration for time or storage, as mentioned by others.
In PowerShell 5 and PowerShell 5 ISE, it is also possible to use just Shift + Enter for multiline editing (instead of standard backticks `
at the end of each line):
PS> &"C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe" # Shift+Enter
>>> -verb:sync # Shift+Enter
>>> -source:contentPath="c:\workspace\xxx\master\Build\_PublishedWebsites\xxx.Web" # Shift+Enter
>>> -dest:contentPath="c:\websites\xxx\wwwroot,computerName=192.168.1.1,username=administrator,password=xxx"
Or for larger arrays, all with the same value:
$m_by_n_array = array_fill(0, $n, array_fill(0, $m, $value);
will create an $m
by $n
array with everything set to $value
.
Kotlin Version
Use below snippet to add a drawable left to the button:
val drawable = ContextCompat.getDrawable(context, R.drawable.ic_favorite_white_16dp)
button.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null)
.
Important Point in Using Android Vector Drawable
When you are using an android vector drawable and want to have backward compatibility for API below 21, add the following codes to:
In app level build.gradle
:
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
In Application class:
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
}
}
Try powershell's switch statement as an alternative, especially for variable assignment - multiple lines, but readable.
Example,
$WinVer = switch ( Test-Path $Env:windir\SysWOW64 ) {
$true { "64-bit" }
$false { "32-bit" }
}
"This version of Windows is $WinVer"
By the way, if you are trying to find a way to send double quotes to the device, try the following:
adb shell input text '\"'
I'm not sure why there's no event code for quotes, but this workaround does the job. Also, if you're using MonkeyDevice (or ChimpChat) you should test each caracter before invoking monkeyDevice.type, otherwise you get nothing when you try to send "
In addition, apparently, this error will happen if you clone into NTFS Ram Drive.
foreach (var item in model.Where(x => !model2.Any(y => y.ID == x.ID)).ToList())
{
enter code here
}
same work you also can do with Contains
secondly Where
is give you new list of values.
thirdly using Exist
is not a good practice, you can achieve your target from Any
and contains
like
EmployeeDetail _E = Db.EmployeeDetails.where(x=>x.Id==1).FirstOrDefault();
Hope this will clear your confusion.
From Python version 2.6 on you can use multiple arguments to set.intersection()
, like
u = set.intersection(s1, s2, s3)
If the sets are in a list, this translates to:
u = set.intersection(*setlist)
where *a_list
is list expansion
Note that set.intersection
is not a static method, but this uses the functional notation to apply intersection of the first set with the rest of the list. So if the argument list is empty this will fail.
Select Table_Name, Count(*) As ColumnCount
From Information_Schema.Columns
Group By Table_Name
Order By Table_Name
This code show a list of tables with a number of columns present in that table for a database.
If you want to know the number of column for a particular table in a database
then simply use where
clause e.g. where Table_Name='name_your_table'
There is much simpler way:
using System;
using System.Collections.Generic;
....
var caseInsensitiveDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
Verify current version of PHP Type in the following to see the current PHP version:
php -v
Should output something like:
PHP 5.3.3 (cli) (built: Jul 9 2015 17:39:00) Copyright (c) 1997-2010 The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
Install the Remi and EPEL RPM repositories
If you haven’t already done so, install the Remi and EPEL repositories
wget https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm && rpm -Uvh epel-release-latest-6.noarch.rpm
wget http://rpms.famillecollet.com/enterprise/remi-release-6.rpm && rpm -Uvh remi-release-6*.rpm
Enable the REMI repository globally:
nano /etc/yum.repos.d/remi.repo
Under the section that looks like [remi] make the following changes:
[remi]
name=Remi's RPM repository for Enterprise Linux 6 - $basearch
#baseurl=http://rpms.remirepo.net/enterprise/6/remi/$basearch/
mirrorlist=http://rpms.remirepo.net/enterprise/6/remi/mirror
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-remi
Also, under the section that looks like [remi-php55] make the following changes:
[remi-php56]
name=Remi's PHP 5.6 RPM repository for Enterprise Linux 6 - $basearch
#baseurl=http://rpms.remirepo.net/enterprise/6/php56/$basearch/
mirrorlist=http://rpms.remirepo.net/enterprise/6/php56/mirror
# WARNING: If you enable this repository, you must also enable "remi"
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-remi
Type CTRL-O to save and CTRL-X to close the editor
Upgrade PHP 5.3 to PHP 5.6 Now we can upgrade PHP. Simply type in the following command:
yum -y upgrade php*
Once the update has completed, let’s verify that you have PHP 5.6 installed:
php -v
Should see output similar to the following:
PHP 5.6.14 (cli) (built: Sep 30 2015 14:07:43)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies
This will give you are simple print within a sql script:
select 'This is a comment' AS '';
Alternatively, this will add some dynamic data to your status update if used directly after an update
, delete
, or insert
command:
select concat ("Updated ", row_count(), " rows") as '';
In mvc 4 Could be rendered with Underscore(" _ ")
Razor:
@Html.ActionLink("Vote", "#", new { id = item.FileId, }, new { @class = "votes", data_fid = item.FileId, data_jid = item.JudgeID, })
Rendered Html
<a class="votes" data-fid="18587" data-jid="9" href="/Home/%23/18587">Vote</a>
SELECT Id 'PatientId',
ISNULL(CONVERT(varchar(50),ParentId),'') 'ParentId'
FROM Patients
ISNULL
always tries to return a result that has the same data type as the type of its first argument. So, if you want the result to be a string (varchar
), you'd best make sure that's the type of the first argument.
COALESCE
is usually a better function to use than ISNULL
, since it considers all argument data types and applies appropriate precedence rules to determine the final resulting data type. Unfortunately, in this case, uniqueidentifier
has higher precedence than varchar
, so that doesn't help.
(It's also generally preferred because it extends to more than two arguments)
Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:
If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php
Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an
iframe
embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.
The best solution I created is to simply use google as the ssl proxy...
https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky
Tested and works in firefox.
Other Methods:
Use a Third party such as embed.ly (but it it really only good for well known http APIs).
Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)
https://example.com
That has a iframe linking to...
https://example.com/utilities/redirect.html
Which has a simple js redirect script like...
document.location.href ="http://thenonsslsite.com";
Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.
You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.
Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).
The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.
Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.
First of all, the .json
attribute is a property that delegates to the request.get_json()
method, which documents why you see None
here.
You need to set the request content type to application/json
for the .json
property and .get_json()
method (with no arguments) to work as either will produce None
otherwise. See the Flask Request
documentation:
This will contain the parsed JSON data if the mimetype indicates JSON (application/json, see
is_json()
), otherwise it will beNone
.
You can tell request.get_json()
to skip the content type requirement by passing it the force=True
keyword argument.
Note that if an exception is raised at this point (possibly resulting in a 400 Bad Request response), your JSON data is invalid. It is in some way malformed; you may want to check it with a JSON validator.
Your function is:
function data(){
$a = "abc";
$b = "def";
$c = "ghi";
return array($a, $b, $c);
}
It returns an array where position 0 is $a, position 1 is $b and position 2 is $c. You can therefore access $a by doing just this:
data()[0]
If you do $myvar = data()[0] and print $myvar, you will get "abc", which was the value assigned to $a inside the function.
In addition to Benjamin's answer (which I've only skimmed), you need to make sure that your files are actually stored using the proper encoding (that would be UTF-8 for source code, JSPs etc., but note that Java Properties files must be encoded as ISO 8859-1 by definition).
The problem with this is that it's not possible to tell what encoding has been used to store a file. Your only option is to open the file using a specific encoding, and checking whether or not the content makes sense. You can also try to convert the file from the assumed encoding to the desired encoding using iconv - if that produces an error, your assumption was incorrect. So if you assume that hello.jsp is encoded as UTF-8, run "iconv -f UTF-16 -t UTF-8 hello.jsp" and check for errors.
If you should find out that your files are not properly encoded, you need to find out why. It's probably the editor or IDE you used to create the file. In case of Eclipse (and STS), make sure the Text File Encoding (Preferences / General / Workspace) is set to UTF-8 (it unfortunately defaults to your system's platform encoding).
What makes encoding problems so difficult to debug is that there's so many components involved (text editor, borwser, plus each and every software component in between, in some cases including a database), and each of them has the potential to introduce an error.
This one worked for me:
def list = [1,2,3,4]
for(item in list){
println item
}
Source: Wikia.
As others have stated, your code is basically correct though the outer try
is unneeded. Here are a few more thoughts.
DataSource
Other answers here are correct and good, such the accepted Answer by bpgergo. But none of the show the use of DataSource
, commonly recommended over use of DriverManager
in modern Java.
So for the sake of completeness, here is a complete example that fetches the current date from the database server. The database used here is Postgres. Any other database would work similarly. You would replace the use of org.postgresql.ds.PGSimpleDataSource
with an implementation of DataSource
appropriate to your database. An implementation is likely provided by your particular driver, or connection pool if you go that route.
A DataSource
implementation need not be closed, because it is never “opened”. A DataSource
is not a resource, is not connected to the database, so it is not holding networking connections nor resources on the database server. A DataSource
is simply information needed when making a connection to the database, with the database server's network name or address, the user name, user password, and various options you want specified when a connection is eventually made. So your DataSource
implementation object does not go inside your try-with-resources parentheses.
Your code makes proper used of nested try-with-resources statements.
Notice in the example code below that we also use the try-with-resources syntax twice, one nested inside the other. The outer try
defines two resources: Connection
and PreparedStatement
. The inner try
defines the ResultSet
resource. This is a common code structure.
If an exception is thrown from the inner one, and not caught there, the ResultSet
resource will automatically be closed (if it exists, is not null). Following that, the PreparedStatement
will be closed, and lastly the Connection
is closed. Resources are automatically closed in reverse order in which they were declared within the try-with-resource statements.
The example code here is overly simplistic. As written, it could be executed with a single try-with-resources statement. But in a real work you will likely be doing more work between the nested pair of try
calls. For example, you may be extracting values from your user-interface or a POJO, and then passing those to fulfill ?
placeholders within your SQL via calls to PreparedStatement::set…
methods.
Notice that the semicolon trailing the last resource statement within the parentheses of the try-with-resources is optional. I include it in my own work for two reasons: Consistency and it looks complete, and it makes copy-pasting a mix of lines easier without having to worry about end-of-line semicolons. Your IDE may flag the last semicolon as superfluous, but there is no harm in leaving it.
New in Java 9 is an enhancement to try-with-resources syntax. We can now declare and populate the resources outside the parentheses of the try
statement. I have not yet found this useful for JDBC resources, but keep it in mind in your own work.
ResultSet
should close itself, but may notIn an ideal world the ResultSet
would close itself as the documentation promises:
A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.
Unfortunately, in the past some JDBC drivers infamously failed to fulfill this promise. As a result, many JDBC programmers learned to explicitly close all their JDBC resources including Connection
, PreparedStatement
, and ResultSet
too. The modern try-with-resources syntax has made doing so easier, and with more compact code. Notice that the Java team went to the bother of marking ResultSet
as AutoCloseable
, and I suggest we make use of that. Using a try-with-resources around all your JDBC resources makes your code more self-documenting as to your intentions.
package work.basil.example;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.Objects;
public class App
{
public static void main ( String[] args )
{
App app = new App();
app.doIt();
}
private void doIt ( )
{
System.out.println( "Hello World!" );
org.postgresql.ds.PGSimpleDataSource dataSource = new org.postgresql.ds.PGSimpleDataSource();
dataSource.setServerName( "1.2.3.4" );
dataSource.setPortNumber( 5432 );
dataSource.setDatabaseName( "example_db_" );
dataSource.setUser( "scott" );
dataSource.setPassword( "tiger" );
dataSource.setApplicationName( "ExampleApp" );
System.out.println( "INFO - Attempting to connect to database: " );
if ( Objects.nonNull( dataSource ) )
{
String sql = "SELECT CURRENT_DATE ;";
try (
Connection conn = dataSource.getConnection() ;
PreparedStatement ps = conn.prepareStatement( sql ) ;
)
{
… make `PreparedStatement::set…` calls here.
try (
ResultSet rs = ps.executeQuery() ;
)
{
if ( rs.next() )
{
LocalDate ld = rs.getObject( 1 , LocalDate.class );
System.out.println( "INFO - date is " + ld );
}
}
}
catch ( SQLException e )
{
e.printStackTrace();
}
}
System.out.println( "INFO - all done." );
}
}
You are mixing razor and aspx syntax,if your view engine is razor just do this:
<button class="btn btn-info" type="button" id="addressSearch"
onclick="location.href='@Url.Action("List", "Search")'">
A 2D and 3D solution
Consider a change of basis such that the line segment becomes (0, 0, 0)-(d, 0, 0)
and the point (u, v, 0)
. The shortest distance occurs in that plane and is given by
u = 0 -> d(A, C)
0 = u = d -> |v|
d = u -> d(B, C)
(the distance to one of the endpoints or to the supporting line, depending on the projection to the line. The iso-distance locus is made of two half-circles and two line segments.)
In the above expression, d is the length of the segment AB, and u, v are respectivey the scalar product and (modulus of the) cross product of AB/d (unit vector in the direction of AB) and AC. Hence vectorially,
AB.AC = 0 -> |AC|
0 = AB.AC = AB² -> |ABxAC|/|AB|
AB² = AB.AC -> |BC|
Do not use Math.Pow
When i use
for (int i = 0; i < 10e7; i++)
{
var x3 = x * x * x;
var y3 = y * y * y;
}
It only takes 230 ms whereas the following takes incredible 7050 ms:
for (int i = 0; i < 10e7; i++)
{
var x3 = Math.Pow(x, 3);
var y3 = Math.Pow(x, 3);
}
Had same problem with some non-licensed cables. Works fine with Apple's & Belkin's USB cables.
for followers, this error message can also mean "you have it referencing a foreign object that hasn't been saved to the DB yet" (even though it's there, and is non null).
Look at stat
for checking if the directory exists,
And mkdir
, to create a directory.
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
struct stat st = {0};
if (stat("/some/directory", &st) == -1) {
mkdir("/some/directory", 0700);
}
You can see the manual of these functions with the man 2 stat
and man 2 mkdir
commands.
Have you tried adding a configsection
handler to your app.config? e.g.
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
You're reading too many files. Node reads files asynchronously, it'll be reading all files at once. So you're probably reading the 10240 limit.
See if this works:
var fs = require('fs')
var events = require('events')
var util = require('util')
var path = require('path')
var FsPool = module.exports = function(dir) {
events.EventEmitter.call(this)
this.dir = dir;
this.files = [];
this.active = [];
this.threads = 1;
this.on('run', this.runQuta.bind(this))
};
// So will act like an event emitter
util.inherits(FsPool, events.EventEmitter);
FsPool.prototype.runQuta = function() {
if(this.files.length === 0 && this.active.length === 0) {
return this.emit('done');
}
if(this.active.length < this.threads) {
var name = this.files.shift()
this.active.push(name)
var fileName = path.join(this.dir, name);
var self = this;
fs.stat(fileName, function(err, stats) {
if(err)
throw err;
if(stats.isFile()) {
fs.readFile(fileName, function(err, data) {
if(err)
throw err;
self.active.splice(self.active.indexOf(name), 1)
self.emit('file', name, data);
self.emit('run');
});
} else {
self.active.splice(self.active.indexOf(name), 1)
self.emit('dir', name);
self.emit('run');
}
});
}
return this
};
FsPool.prototype.init = function() {
var dir = this.dir;
var self = this;
fs.readdir(dir, function(err, files) {
if(err)
throw err;
self.files = files
self.emit('run');
})
return this
};
var fsPool = new FsPool(__dirname)
fsPool.on('file', function(fileName, fileData) {
console.log('file name: ' + fileName)
console.log('file data: ', fileData.toString('utf8'))
})
fsPool.on('dir', function(dirName) {
console.log('dir name: ' + dirName)
})
fsPool.on('done', function() {
console.log('done')
});
fsPool.init()