Starting with 1.6.4, Arduino IDE can be used to program and upload the NodeMCU board by installing the ESP8266 third-party platform package (refer https://github.com/esp8266/Arduino):
To install additional ESP8266WiFi library:
After above steps, you should compile the sketch normally.
Set Copy Enbale to true in netstandard.dll properties.
Open Solution Explorer and right click on netstandard.dll. Set Copy Local to true.
I had the same problem, and my solution was to eliminate the line
android:screenOrientation="portrait"
and then add this in the activity:
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
For the Collatz problem, you can get a significant boost in performance by caching the "tails". This is a time/memory trade-off. See: memoization (https://en.wikipedia.org/wiki/Memoization). You could also look into dynamic programming solutions for other time/memory trade-offs.
Example python implementation:
import sys
inner_loop = 0
def collatz_sequence(N, cache):
global inner_loop
l = [ ]
stop = False
n = N
tails = [ ]
while not stop:
inner_loop += 1
tmp = n
l.append(n)
if n <= 1:
stop = True
elif n in cache:
stop = True
elif n % 2:
n = 3*n + 1
else:
n = n // 2
tails.append((tmp, len(l)))
for key, offset in tails:
if not key in cache:
cache[key] = l[offset:]
return l
def gen_sequence(l, cache):
for elem in l:
yield elem
if elem in cache:
yield from gen_sequence(cache[elem], cache)
raise StopIteration
if __name__ == "__main__":
le_cache = {}
for n in range(1, 4711, 5):
l = collatz_sequence(n, le_cache)
print("{}: {}".format(n, len(list(gen_sequence(l, le_cache)))))
print("inner_loop = {}".format(inner_loop))
This issue started occurring for me all of a sudden, so I was sure, there could be some other reason. On digging deep, it was a simple issue where I used http
in the BaseUrl of Retrofit instead of https
. So changing it to https
solved the issue for me.
...Just open this answer for edit to see it.
Nested lists, deeper levels: ---- leave here an empty row * first level A item - no space in front the bullet character * second level Aa item - 1 space is enough * third level Aaa item - 5 spaces min * second level Ab item - 4 spaces possible too * first level B item
Nested lists, deeper levels:
first level B item
Nested lists, deeper levels:
...Skip a line and indent eight spaces. (as said in the editor-help, just on this page)
* first level A item - no space in front the bullet character
* second level Aa item - 1 space is enough
* third level Aaa item - 5 spaces min
* second level Ab item - 4 spaces possible too
* first level B item
Right click on your website go to property pages and check both the check-boxes under Accessibility validation click on ok. run the website.
The role you have created is not allowed to log in. You have to give the role permission to log in.
One way to do this is to log in as the postgres
user and update the role:
psql -U postgres
Once you are logged in, type:
ALTER ROLE "asunotest" WITH LOGIN;
Here's the documentation http://www.postgresql.org/docs/9.0/static/sql-alterrole.html
In okhttp v4.* I got it working that way
// import the extensions!
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
// ...
json : String = "..."
val JSON : MediaType = "application/json; charset=utf-8".toMediaType()
val jsonBody: RequestBody = json.toRequestBody(JSON)
// go on with Request.Builder() etc
You can use a pseudo-element to insert that character before each list item:
ul {_x000D_
list-style: none;_x000D_
}_x000D_
_x000D_
ul li:before {_x000D_
content: '?';_x000D_
}
_x000D_
<ul>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
</ul>
_x000D_
As, i am installing through anaconda Prompt .In my case, it didn't even work with python -m pip install
Then, i add this
python -m pip install <package_name> --user
It works for me.
Like: python -m pip install mitmproxy --user
Another you should try that run the Command Prompt as Run as Administrator and then try pip install. It should work either.
{/*_x000D_
<Header />_x000D_
<Content />_x000D_
<MapList />_x000D_
<HelloWorld />_x000D_
*/}
_x000D_
My error was define the view like this:
view = inflater.inflate(R.layout.qr_fragment, container);
It was missing:
view = inflater.inflate(R.layout.qr_fragment, container, false);
If the insertion point of the new object does not need to match the previous object's index then the simplest way to do this with lodash is by using _.reject
and then pushing new values in to the array:
var arr = [
{ id: 1, name: "Person 1" },
{ id: 2, name: "Person 2" }
];
arr = _.reject(arr, { id: 1 });
arr.push({ id: 1, name: "New Val" });
// result will be: [{ id: 2, name: "Person 2" }, { id: 1, name: "New Val" }]
If you have multiple values that you want to replace in one pass, you can do the following (written in non-ES6 format):
var arr = [
{ id: 1, name: "Person 1" },
{ id: 2, name: "Person 2" },
{ id: 3, name: "Person 3" }
];
idsToReplace = [2, 3];
arr = _.reject(arr, function(o) { return idsToReplace.indexOf(o.id) > -1; });
arr.push({ id: 3, name: "New Person 3" });
arr.push({ id: 2, name: "New Person 2" });
// result will be: [{ id: 1, name: "Person 1" }, { id: 3, name: "New Person 3" }, { id: 2, name: "New Person 2" }]
As the whole thing is mixing up let's look at it function and code to simulate what it means consicely
The only way to get a row is via primary key
getRow(pk: PrimaryKey): Row
Primary key data structure can be this:
// If you decide your primary key is just the partition key.
class PrimaryKey(partitionKey: String)
// and in thids case
getRow(somePartitionKey): Row
However you can decide your primary key is partition key + sort key in this case:
// if you decide your primary key is partition key + sort key
class PrimaryKey(partitionKey: String, sortKey: String)
getRow(partitionKey, sortKey): Row
getMultipleRows(partitionKey): Row[]
So the bottom line:
Decided that your primary key is partition key only? get single row by partition key.
Decided that your primary key is partition key + sort key? 2.1 Get single row by (partition key, sort key) or get range of rows by (partition key)
In either way you get a single row by primary key the only question is if you defined that primary key to be partition key only or partition key + sort key
Building blocks are:
Think of Item as a row and of KV Attribute as cells in that row.
You can do (2) only if you decided that your PK is composed of (HashKey, SortKey).
More visually as its complex, the way I see it:
+----------------------------------------------------------------------------------+
|Table |
|+------------------------------------------------------------------------------+ |
||Item | |
||+-----------+ +-----------+ +-----------+ +-----------+ | |
|||primaryKey | |kv attr | |kv attr ...| |kv attr ...| | |
||+-----------+ +-----------+ +-----------+ +-----------+ | |
|+------------------------------------------------------------------------------+ |
|+------------------------------------------------------------------------------+ |
||Item | |
||+-----------+ +-----------+ +-----------+ +-----------+ +-----------+ | |
|||primaryKey | |kv attr | |kv attr ...| |kv attr ...| |kv attr ...| | |
||+-----------+ +-----------+ +-----------+ +-----------+ +-----------+ | |
|+------------------------------------------------------------------------------+ |
| |
+----------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------+
|1. Always get item by PrimaryKey |
|2. PK is (Hash,RangeKey), great get MULTIPLE Items by Hash, filter/sort by range |
|3. PK is HashKey: just get a SINGLE ITEM by hashKey |
| +--------------------------+|
| +---------------+ |getByPK => getBy(1 ||
| +-----------+ +>|(HashKey,Range)|--->|hashKey, > < or startWith ||
| +->|Composite |-+ +---------------+ |of rangeKeys) ||
| | +-----------+ +--------------------------+|
|+-----------+ | |
||PrimaryKey |-+ |
|+-----------+ | +--------------------------+|
| | +-----------+ +---------------+ |getByPK => get by specific||
| +->|HashType |-->|get one item |--->|hashKey ||
| +-----------+ +---------------+ | ||
| +--------------------------+|
+----------------------------------------------------------------------------------+
So what is happening above. Notice the following observations. As we said our data belongs to (Table, Item, KVAttribute). Then Every Item has a primary key. Now the way you compose that primary key is meaningful into how you can access the data.
If you decide that your PrimaryKey is simply a hash key then great you can get a single item out of it. If you decide however that your primary key is hashKey + SortKey then you could also do a range query on your primary key because you will get your items by (HashKey + SomeRangeFunction(on range key)). So you can get multiple items with your primary key query.
Note: I did not refer to secondary indexes.
According to official documentation: Creating REST Controllers with the @RestController annotation
@RestController is a stereotype annotation that combines @ResponseBody and @Controller. More than that, it gives more meaning to your Controller and also may carry additional semantics in future releases of the framework.
It seems that it's best to use @RestController
for clarity, but you can also combine it with ResponseEntity
for flexibility when needed (According to official tutorial and the code here and my question to confirm that).
For example:
@RestController
public class MyController {
@GetMapping(path = "/test")
@ResponseStatus(HttpStatus.OK)
public User test() {
User user = new User();
user.setName("Name 1");
return user;
}
}
is the same as:
@RestController
public class MyController {
@GetMapping(path = "/test")
public ResponseEntity<User> test() {
User user = new User();
user.setName("Name 1");
HttpHeaders responseHeaders = new HttpHeaders();
// ...
return new ResponseEntity<>(user, responseHeaders, HttpStatus.OK);
}
}
This way, you can define ResponseEntity
only when needed.
Update
You can use this:
return ResponseEntity.ok().headers(responseHeaders).body(user);
I got the similar problem, Shows icons in square, tried as per the instructions specified here : https://fontawesome.com/how-to-use/on-the-web/setup/hosting-font-awesome-yourself
Resolved by using this reference in head section of html page
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/all.css">
Put [unowned self]
before (text: String)...
in your closure. This is called a capture list and places ownership instructions on symbols captured in the closure.
If none of the above makes sense:
tl;dr
Just like an
implicitly unwrapped optional
, If you can guarantee that the reference will not be nil at its point of use, use unowned. If not, then you should be using weak.
Explanation:
I retrieved the following below at: weak unowned link. From what I gathered, unowned self can't be nil but weak self can be, and unowned self can lead to dangling pointers...something infamous in Objective-C. Hope it helps
"UNOWNED Weak and unowned references behave similarly but are NOT the same."
Unowned references, like weak references, do not increase the retain count of the object being referred. However, in Swift, an unowned reference has the added benefit of not being an Optional. This makes them easier to manage rather than resorting to using optional binding. This is not unlike Implicitly Unwrapped Optionals . In addition, unowned references are non-zeroing. This means that when the object is deallocated, it does not zero out the pointer. This means that use of unowned references can, in some cases, lead to dangling pointers. For you nerds out there that remember the Objective-C days like I do, unowned references map to unsafe_unretained references.
This is where it gets a little confusing.
Weak and unowned references both do not increase retain counts.
They can both be used to break retain cycles. So when do we use them?!
According to Apple's docs:
“Use a weak reference whenever it is valid for that reference to become nil at some point during its lifetime. Conversely, use an unowned reference when you know that the reference will never be nil once it has been set during initialisation.”
I've seen occasional problems with Eclipse forgetting that built-in classes (including Object
and String
) exist. The way I've resolved them is to:
This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.
As of Xcode 7 you can turn on Fast, Whole Module Optimization
. This should increase your performance immediately.
You can use this Firefox addon to download all files in HTTP Directory.
https://addons.mozilla.org/en-US/firefox/addon/http-directory-downloader/
In my case it was that the C: drive was out of space. Ensure that you have enough space available.
It can happen if the JDK version is different.
try this with maven:
<properties>
<jdk.version>1.8</jdk.version>
</properties>
under build->plugins:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
It's an eclipse setup issue, not a Jersey issue.
From this thread ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer
Right click your eclipse project Properties -> Deployment Assembly -> Add -> Java Build Path Entries -> Gradle Dependencies -> Finish.
So Eclipse wasn't using the Gradle dependencies when Apache was starting .
better to use touchstart
event with .on()
jQuery method:
$(window).load(function() { // better to use $(document).ready(function(){
$('.List li').on('click touchstart', function() {
$('.Div').slideDown('500');
});
});
And i don't understand why you are using $(window).load()
method because it waits for everything on a page to be loaded, this tend to be slow, while you can use $(document).ready()
method which does not wait for each element on the page to be loaded first.
This is the code I ended up using. It stretches input & output cells to the left and right. Note that the input/output number indication will be gone:
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
display(HTML("<style>.output_result { max-width:100% !important; }</style>"))
display(HTML("<style>.prompt { display:none !important; }</style>"))
I got the same problem and this is how i solved. :
Things to check when enabling the bundle optimization;
BundleTable.EnableOptimizations = true;
and
webconfig debug = "false"
bundles.IgnoreList.Clear();
this will ignore the minified assets of your bundles like *.min.css
or *.min.js
which can cause an undefine error of your script. To fix is replace the .min
asset to original. if you do this you may not need the bundles.IgnoreList.Clear();
e.g.
bundles.Add(new ScriptBundle("~/bundles/datatablesjs")
.Include("~/Scripts/datatables.min.js") <---- change this to non minified ver.
Make sure the names of the bundles of your css and js are unique.
bundles.Add(new StyleBundle("~/bundles/datatablescss").Include( ...) );
bundles.Add(new ScriptBundle("~/bundles/datatablesjs").Include( ...) );
Make sure you use the Render name of your @Script.Render and Style.Render are the same on your bundle config. e.g.
@Styles.Render("~/bundles/datatablescss")
@Scripts.Render("~/bundles/datatablesjs")
Edited ZygD's answer for python 3.x.:
import re
import urllib.request
import string
url1 = input("Please enter a URL from Tunein Radio: ");
request = urllib.request.Request(url1);
response = urllib.request.urlopen(request);
raw_file = response.read().decode('utf-8');
API_key = re.findall(r"StreamUrl\":\"(.*?),\"",raw_file);
#print API_key;
#print "The API key is: " + API_key[0];
request2 = urllib.request.Request(str(API_key[0]));
response2 = urllib.request.urlopen(request2);
key_content = response2.read().decode('utf-8');
raw_stream_url = re.findall(r"Url\": \"(.*?)\"",key_content);
bandwidth = re.findall(r"Bandwidth\":(.*?),", key_content);
reliability = re.findall(r"lity\":(.*?),", key_content);
isPlaylist = re.findall(r"HasPlaylist\":(.*?),",key_content);
codec = re.findall(r"MediaType\": \"(.*?)\",", key_content);
tipe = re.findall(r"Type\": \"(.*?)\"", key_content);
total = 0
for element in raw_stream_url:
total = total + 1
i = 0
print ("I found " + str(total) + " streams.");
for element in raw_stream_url:
print ("Stream #" + str(i + 1));
print ("Stream stats:");
print ("Bandwidth: " + str(bandwidth[i]) + " kilobytes per second.");
print ("Reliability: " + str(reliability[i]) + "%");
print ("HasPlaylist: " + str(isPlaylist[i]));
print ("Stream codec: " + str(codec[i]));
print ("This audio stream is " + tipe[i].lower());
print ("Pure streaming URL: " + str(raw_stream_url[i]));
i = i + 1
input("Press enter to close")
I have several projects in a solution. For some of the projects, I previously added the references manually. When I used NuGet to update the WebAPI package, those references were not updated automatically.
I found out that I can either manually update those reference so they point to the v5 DLL inside the Packages folder of my solution or do the following.
From your post, I understand that you cannot set the width to your li.
How about this?
ul {
border:2px solid red;
display:inline-block;
}
li {
display:inline;
padding:0 30%; /* try adjusting the side % to give a feel of center aligned.*/
}
_x000D_
<ul>
<li>Hello</li>
<li>Hezkdhkfskdhfkllo</li>
<li>Hello</li>
</ul>
_x000D_
Here's a demo. http://codepen.io/anon/pen/HhBwx
chdmod works for my under debian (proxmox):
# chmod a+rw /dev/ttyACM0
For installing arduino IDE:
# apt-get install arduino arduino-core arduino-mk
Add the user to dialout group:
# gpasswd -a user dialout
Restart Linux.
Try with the File > Examples > 01.Basic > Blink, change the 2 delays to delay(60) and click the upload button for testing on arduino, led must blink faster. ;)
Thanks to Novocaine88's answer to use a try catch loop I have successfully received an error message when I caused one.
<?php
$dbhost = "localhost";
$dbname = "pdo";
$dbusername = "root";
$dbpassword = "845625";
$link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$statement = $link->prepare("INERT INTO testtable(name, lastname, age)
VALUES(?,?,?)");
$statement->execute(array("Bob","Desaunois",18));
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
In the following code instead of INSERT INTO it says INERT.
this is the error I got.
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INERT INTO testtable(name, lastname, age) VALUES('Bob','Desaunoi' at line 1
When I "fix" the issue, it works as it should. Thanks alot everyone!
Make sure that Access less secure app is allowed.
MailMessage mail = new MailMessage();
mail.From = new MailAddress("[email protected]");
mail.Sender = new MailAddress("[email protected]");
mail.To.Add("external@emailaddress");
mail.IsBodyHtml = true;
mail.Subject = "Email Sent";
mail.Body = "Body content from";
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "xx");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.EnableSsl = true;
smtp.Timeout = 30000;
try
{
smtp.Send(mail);
}
catch (SmtpException e)
{
textBox1.Text= e.Message;
}
In my case
li {
list-style-type : none;
}
It doesn't show the bullet but leaved some space for the bullet.
I use
li {
list-style-type : '';
}
It works perfectly.
WARNING: size()
was deprecated in jQuery 1.8 and removed in jQuery 3.0, use .length
instead
Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/
$(document).ready(function () {
size_li = $("#myList li").size();
x=3;
$('#myList li:lt('+x+')').show();
$('#loadMore').click(function () {
x= (x+5 <= size_li) ? x+5 : size_li;
$('#myList li:lt('+x+')').show();
});
$('#showLess').click(function () {
x=(x-5<0) ? 3 : x-5;
$('#myList li').not(':lt('+x+')').hide();
});
});
$(document).ready(function () {
size_li = $("#myList li").size();
x=3;
$('#myList li:lt('+x+')').show();
$('#loadMore').click(function () {
x= (x+5 <= size_li) ? x+5 : size_li;
$('#myList li:lt('+x+')').show();
$('#showLess').show();
if(x == size_li){
$('#loadMore').hide();
}
});
$('#showLess').click(function () {
x=(x-5<0) ? 3 : x-5;
$('#myList li').not(':lt('+x+')').hide();
$('#loadMore').show();
$('#showLess').show();
if(x == 3){
$('#showLess').hide();
}
});
});
CSS
#showLess {
color:red;
cursor:pointer;
display:none;
}
Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/2/
In connection string, the first string is the base in web.config
SchedulingContext is the base parameter of Entity file.
<connectionStrings>
<add name="SchedulingContext" connectionString="Data Source=XXX\SQL2008R2DEV;Initial Catalog=YYY;Persist Security Info=True;User ID=sa;Password=XXX" providerName="System.Data.SqlClient"/>
For Ubuntu Users, the code_editor.xml
is in
/usr/share/mysql-workbench/data
edit as you need, In Ubuntu which is a must need, some default used colours lacks contrast and it is unable to read, For a quick workaround you can also use this solution.
Visit this repo to get the full XML file.
Make sure the value in the child's project/parent/version node matches its parent's project/version value
I think I found solution - proper binary parser must be selected so Eclipse can recognize the executable:
Select the project, then right-click. Project->Properties->C/C++ Build->Settings->Binary Parsers, PE Windows Parser.
I.e. if Cygwin compiler is used then Cygwin parser should be used.
That worked for me at least for Cross-compiler (both on Windows 7 and Ubuntu 12.04). On Linux, I use Elf parser.
If anyone has the better solution, please advise.
check the following link https://www.geeksforgeeks.org/how-to-create-an-unordered_map-of-user-defined-class-in-cpp/ for more details.
You need to use RegularExpression Attribute, something like this:
[RegularExpression("^[a-zA-Z0-9_\\.-]+@([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$", ErrorMessage = "E-mail is not valid")]
And don't delete [Required] because [RegularExpression] doesn't affect empty fields.
The problem occurred due to the Control validator. Just Add the J Query reference to your web page as follows and then add the Validation Settings in your web.config file to overcome the problem. I too faced the same problem and the below gave the solution to my problem.
Step1:
Step2 :
It will resolve your problem.
You can also post runnable using the view from any other thread. But be sure that the view is not null:
tView.post(new Runnable() {
@Override
public void run() {
tView.setText("Success");
}
});
According to the Documentation:
"boolean post (Runnable action) Causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread."
If you can't edit this part of code where your dict was defined you can still order it at any point in any way you want, like this:
from collections import OrderedDict
order_of_keys = ["key1", "key2", "key3", "key4", "key5"]
list_of_tuples = [(key, your_dict[key]) for key in order_of_keys]
your_dict = OrderedDict(list_of_tuples)
Besides the powerful options on the "Run Configurations.." on a well configured project you'll see the maven tasks on the Run As as well.
You can resolve it by configuring settings.xml in Eclipse.
Go to Window --> Preferences --> Maven --> User Settings --> select the actual path of settings.xml
The problem is that you're using the buttons as part of your lists. And because the vertical margin between list items is too low to place the buttons in between it messes the alignments up. I would place one of the buttons on top of the list and another one beneath them so that it would look like what you expect!
<ul>
<input class="btn pull-right" value="test">
<li>One</li>
<li>Two</li>
<input class="btn pull-right" value="test2">
</ul>
For me:
It was Eclipse v4.5 (Mars) which did not support Java SE 7, so I added Java SE 8. It worked.
i found the solution. i have installed 2 versions of jre sdk 1.3 and jre7 so i uninstall the older version sdk1.3 then it works.
Even better!
long tStart = System.nanoTime();
long tEnd = System.nanoTime();
long tRes = tEnd - tStart; // time in nanoseconds
Read the documentation about nanoTime()!
Sets are unordered, as you say. Even though one way to implement sets is using a tree, they can also be implemented using a hash table (meaning getting the keys in sorted order may not be that trivial).
If you'd like to sort them, you can simply perform:
sorted(set(y))
which will produce a sorted list containing the set's elements. (Not a set. Again, sets are unordered.)
Otherwise, the only thing guaranteed by set
is that it makes the elements unique (nothing will be there more than once).
Hope this helps!
Server
import java.net.*;
import java.io.*;
import java.util.*;
import javax.net.ssl.*;
import javax.net.*;
class Test{
public static void main(String[] args){
try{
SSLContext context = SSLContext.getInstance("TLSv1.2");
context.init(null,null,null);
SSLServerSocketFactory serverSocketFactory = context.getServerSocketFactory();
SSLServerSocket server = (SSLServerSocket)serverSocketFactory.createServerSocket(1024);
server.setEnabledCipherSuites(server.getSupportedCipherSuites());
SSLSocket socket = (SSLSocket)server.accept();
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
System.out.println(in.readInt());
}catch(Exception e){e.printStackTrace();}
}
}
Client
import java.net.*;
import java.io.*;
import java.util.*;
import javax.net.ssl.*;
import javax.net.*;
class Test2{
public static void main(String[] args){
try{
SSLContext context = SSLContext.getInstance("TLSv1.2");
context.init(null,null,null);
SSLSocketFactory socketFactory = context.getSocketFactory();
SSLSocket socket = (SSLSocket)socketFactory.createSocket("localhost", 1024);
socket.setEnabledCipherSuites(socket.getSupportedCipherSuites());
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeInt(1337);
}catch(Exception e){e.printStackTrace();}
}
}
server.setEnabledCipherSuites(server.getSupportedCipherSuites()); socket.setEnabledCipherSuites(socket.getSupportedCipherSuites());
The issue here is that input()
returns a string in Python 3.x, so when you do your comparison, you are comparing a string and an integer, which isn't well defined (what if the string is a word, how does one compare a string and a number?) - in this case Python doesn't guess, it throws an error.
To fix this, simply call int()
to convert your string to an integer:
int(input(...))
As a note, if you want to deal with decimal numbers, you will want to use one of float()
or decimal.Decimal()
(depending on your accuracy and speed needs).
Note that the more pythonic way of looping over a series of numbers (as opposed to a while
loop and counting) is to use range()
. For example:
def main():
print("Let me Retire Financial Calculator")
deposit = float(input("Please input annual deposit in dollars: $"))
rate = int(input ("Please input annual rate in percentage: %")) / 100
time = int(input("How many years until retirement?"))
value = 0
for x in range(1, time+1):
value = (value * rate) + deposit
print("The value of your account after" + str(x) + "years will be $" + str(value))
The solution is to set the proxy to "native" as below
Go to "Window-> Preferences -> General -> Network Connection" and change the Settings "Active Provider-> Native". It worked for me.
This is the simplest way to do it. CSS only.
ul.list {_x000D_
width: 300px; _x000D_
}_x000D_
_x000D_
ul.list li{_x000D_
display:inline-block;_x000D_
width: 100px;_x000D_
}
_x000D_
<ul class="list">_x000D_
<li>A</li>_x000D_
<li>B</li>_x000D_
<li>C</li>_x000D_
<li>D</li>_x000D_
<li>E</li>_x000D_
</ul>
_x000D_
I had this problem when moving my project from one computer to another. The solution was to reload selenium webdriver from nuget.
Look for "poi-3.17.jar"!!!
Problem solved and errors disappeared.
Ensure that you are using Attributes
(e.g. RequiredAttribute
) which comes under System.ComponentModel.DataAnnotations
namespace
You can do it this way:
(Edit: Considering that you're waiting for a response json
with dataType: 'json'
)
.NET
public JsonResult Edit(EditPostViewModel data)
{
if(ModelState.IsValid)
{
// Save
return Json(new { Ok = true } );
}
return Json(new { Ok = false } );
}
JS:
success: function (data) {
if (data.Ok) {
alert('success');
}
else {
alert('problem');
}
},
If you need I can also explain how to do it by returning a error 500, and get the error in the event error (ajax). But in your case this may be an option
I have the same problem with a footer I'm trying to divide up. I found that this worked for me by trying few of above suggestions combined:
footer div ul {
list-style-position: inside;
padding-left: 0;
}
This seems to keep it to the left under my h1 and the bullet points inside the div rather than outside to the left.
Try this, it is updating the current location, and it works fine.
public void onLocationChanged(@NonNull Location location) {
//here we update the location on the map
LatLng myActualLocation = new LatLng(location.getLatitude(), location.getLongitude());
if (markerName!=null){ // marker name is declared as a gloval variable.
markerName.remove();
}
markerName = mMap.addMarker(new MarkerOptions().position(myActualLocation).title("Marker Miami").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
// mMap.addMarker(new MarkerOptions().position(myActualLocation).title("Marker Miami").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myActualLocation,18));
}
After placing the jar file in desired location, you need to add the jar file by right click on
Project --> properties --> Java Build Path --> Libraries --> Add Jar.
Everything was working fine one second and then my server started giving me this error. I went through all the answers mentioned here and what worked for me was this simple solution:
Deleting the server and then configuring a new one
If you're sure that you didn't change anything and the error just popped up, DO NOT start deleting .snap files or other temp files. Doing that will only cause more problems. And if the error occurred because of some changes made by you, this error is definitely going to be because of some errors in web.xml file.
P.S. Changing the workspace will do you absolutely no good, because if the problem is in your project, then it'll still occur in the new work space when you'll import the project!
I've had my drivers installed and the Arduino connected through an unpowered usb hub. Moving it to an USB port of my computer made it work.
As others have pointed out, output can be buffered within your program before a console or shell has a chance to see it.
On unix-like systems, including macs, stdout
has line-based buffering by default. This means that your program empties its stdout
buffer as soon as it sees a newline.
However, on windows, newlines are no longer special, and full buffering is used. Windows doesn't support line buffering at all; see the msdn page on setvbuf.
So on windows, a good approach is to completely shut off stdout
buffering like so:
setvbuf (stdout, NULL, _IONBF, 0);
For me I was getting the problem when deploying a geoserver WAR
into tomcat 7
To fix it, I was on Java 7 and upgrading to Java 8.
This is running under a docker container. Tomcat 7.0.75
+ Java 8
+ Geos 2.10.2
The answer by Pomber is acceptable, however I'm not a big fan of creating new objects repeatedly. The best solutions are always the ones that try to mitigate memory hog. Yes, there is auto garbage collection but memory conservation in a mobile device falls within the confines of best practice. The code below updates a TextView in a service.
TextViewUpdater textViewUpdater = new TextViewUpdater();
Handler textViewUpdaterHandler = new Handler(Looper.getMainLooper());
private class TextViewUpdater implements Runnable{
private String txt;
@Override
public void run() {
searchResultTextView.setText(txt);
}
public void setText(String txt){
this.txt = txt;
}
}
It can be used from anywhere like this:
textViewUpdater.setText("Hello");
textViewUpdaterHandler.post(textViewUpdater);
I prefer using Hamcrest because it gives much better output in case of a failure
Assert.assertThat(listUnderTest,
IsIterableContainingInOrder.contains(expectedList.toArray()));
Instead of reporting
expected true, got false
it will report
expected List containing "1, 2, 3, ..." got list containing "4, 6, 2, ..."
IsIterableContainingInOrder.contain
According to the Javadoc:
Creates a matcher for Iterables that matches when a single pass over the examined Iterable yields a series of items, each logically equal to the corresponding item in the specified items. For a positive match, the examined iterable must be of the same length as the number of specified items
So the listUnderTest
must have the same number of elements and each element must match the expected values in order.
@Tama, you may want to check this answer: Using Font Awesome icons as bullets
Basically you can accomplish this by using only CSS without the need for the extra markup as suggested by FontAwesome and the other answers here.
In other words, you can accomplish what you need using the same basic markup you mentioned in your initial post:
<ul>
<li>...</li>
<li>...</li>
<li>...</li>
</ul>
Thanks.
It seems like there is a lot of incorrect information about the ValidationSettings:UnobtrusiveValidationMode value. To Disable it you need to do the following.
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
The word None, not WebForms should be used to disable this feature.
print self.id.__str__()
would work for you, although not that useful for you.
Your __str__
method will be more useful when you say want to print out a grid or struct representation as your program develops.
print self._grid.__str__()
def __str__(self):
"""
Return a string representation of the grid for debugging.
"""
grid_str = ""
for row in range(self._rows):
grid_str += str( self._grid[row] )
grid_str += '\n'
return grid_str
Parallel.ForEach
requires a list of user-defined workers and a non-async Action
to perform with each worker.
Task.WaitAll
and Task.WhenAll
require a List<Task>
, which are by definition asynchronous.
I found RiaanDP's response very useful to understand the difference, but it needs a correction for Parallel.ForEach
. Not enough reputation to respond to his comment, thus my own response.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsyncTest
{
class Program
{
class Worker
{
public int Id;
public int SleepTimeout;
public void DoWork(DateTime testStart)
{
var workerStart = DateTime.Now;
Console.WriteLine("Worker {0} started on thread {1}, beginning {2} seconds after test start.",
Id, Thread.CurrentThread.ManagedThreadId, (workerStart - testStart).TotalSeconds.ToString("F2"));
Thread.Sleep(SleepTimeout);
var workerEnd = DateTime.Now;
Console.WriteLine("Worker {0} stopped; the worker took {1} seconds, and it finished {2} seconds after the test start.",
Id, (workerEnd - workerStart).TotalSeconds.ToString("F2"), (workerEnd - testStart).TotalSeconds.ToString("F2"));
}
public async Task DoWorkAsync(DateTime testStart)
{
var workerStart = DateTime.Now;
Console.WriteLine("Worker {0} started on thread {1}, beginning {2} seconds after test start.",
Id, Thread.CurrentThread.ManagedThreadId, (workerStart - testStart).TotalSeconds.ToString("F2"));
await Task.Run(() => Thread.Sleep(SleepTimeout));
var workerEnd = DateTime.Now;
Console.WriteLine("Worker {0} stopped; the worker took {1} seconds, and it finished {2} seconds after the test start.",
Id, (workerEnd - workerStart).TotalSeconds.ToString("F2"), (workerEnd - testStart).TotalSeconds.ToString("F2"));
}
}
static void Main(string[] args)
{
var workers = new List<Worker>
{
new Worker { Id = 1, SleepTimeout = 1000 },
new Worker { Id = 2, SleepTimeout = 2000 },
new Worker { Id = 3, SleepTimeout = 3000 },
new Worker { Id = 4, SleepTimeout = 4000 },
new Worker { Id = 5, SleepTimeout = 5000 },
};
var startTime = DateTime.Now;
Console.WriteLine("Starting test: Parallel.ForEach...");
PerformTest_ParallelForEach(workers, startTime);
var endTime = DateTime.Now;
Console.WriteLine("Test finished after {0} seconds.\n",
(endTime - startTime).TotalSeconds.ToString("F2"));
startTime = DateTime.Now;
Console.WriteLine("Starting test: Task.WaitAll...");
PerformTest_TaskWaitAll(workers, startTime);
endTime = DateTime.Now;
Console.WriteLine("Test finished after {0} seconds.\n",
(endTime - startTime).TotalSeconds.ToString("F2"));
startTime = DateTime.Now;
Console.WriteLine("Starting test: Task.WhenAll...");
var task = PerformTest_TaskWhenAll(workers, startTime);
task.Wait();
endTime = DateTime.Now;
Console.WriteLine("Test finished after {0} seconds.\n",
(endTime - startTime).TotalSeconds.ToString("F2"));
Console.ReadKey();
}
static void PerformTest_ParallelForEach(List<Worker> workers, DateTime testStart)
{
Parallel.ForEach(workers, worker => worker.DoWork(testStart));
}
static void PerformTest_TaskWaitAll(List<Worker> workers, DateTime testStart)
{
Task.WaitAll(workers.Select(worker => worker.DoWorkAsync(testStart)).ToArray());
}
static Task PerformTest_TaskWhenAll(List<Worker> workers, DateTime testStart)
{
return Task.WhenAll(workers.Select(worker => worker.DoWorkAsync(testStart)));
}
}
}
The resulting output is below. Execution times are comparable. I ran this test while my computer was doing the weekly anti virus scan. Changing the order of the tests did change the execution times on them.
Starting test: Parallel.ForEach...
Worker 1 started on thread 9, beginning 0.02 seconds after test start.
Worker 2 started on thread 10, beginning 0.02 seconds after test start.
Worker 3 started on thread 11, beginning 0.02 seconds after test start.
Worker 4 started on thread 13, beginning 0.03 seconds after test start.
Worker 5 started on thread 14, beginning 0.03 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.02 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.02 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.03 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.03 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.03 seconds after the test start.
Test finished after 5.03 seconds.
Starting test: Task.WaitAll...
Worker 1 started on thread 9, beginning 0.00 seconds after test start.
Worker 2 started on thread 9, beginning 0.00 seconds after test start.
Worker 3 started on thread 9, beginning 0.00 seconds after test start.
Worker 4 started on thread 9, beginning 0.00 seconds after test start.
Worker 5 started on thread 9, beginning 0.01 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.01 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.01 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.01 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.01 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.01 seconds after the test start.
Test finished after 5.01 seconds.
Starting test: Task.WhenAll...
Worker 1 started on thread 9, beginning 0.00 seconds after test start.
Worker 2 started on thread 9, beginning 0.00 seconds after test start.
Worker 3 started on thread 9, beginning 0.00 seconds after test start.
Worker 4 started on thread 9, beginning 0.00 seconds after test start.
Worker 5 started on thread 9, beginning 0.00 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.00 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.00 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.00 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.00 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.01 seconds after the test start.
Test finished after 5.01 seconds.
I got the same error after a Java version update. I just edited the line after "-vm" in the eclipse.ini file, which was pointing to the older and no more existing jre path, and everything worked fine.
In my case finish()
executed immediately after a dialog has shown.
This is a bug in the Android Connector for M2E (m2e-android) that was recently fixed:
https://github.com/rgladwell/m2e-android/commit/2b490f900153cd34fff1cec47fe5aeffabe44d87
This fix has been merged and will be available with the next release. In the meantime you can test the new fix by installing from the following update site:
If you set the following property to false then it will disable both bundling and minification.
In Global.asax.cs file, add the line as mentioned below
protected void Application_Start()
{
System.Web.Optimization.BundleTable.EnableOptimizations = false;
}
There is a documentation in SLf4J site to resolve this. I followed that and added slf4j-simple-1.6.1.jar to my aplication along with slf4j-api-1.6.1.jar which i already had.This solved my problem
For me it helped to simply close the edited source file and reopen it. If this doesn't work THEN you can try restarting whole IDE.
Go into your AndroidManifest.xml file
Enjoy using a gui rather then messing with an image editor! Hope this helps!
Brad Wilson has a couple great articles on unobtrusive validation and unobtrusive ajax.
It is also shown very nicely in this Pluralsight video in the section on " AJAX and JavaScript".
Basically, it is simply Javascript validation that doesn't pollute your source code with its own validation code. This is done by making use of data-
attributes in HTML.
If above answers did not work for you then just click this link https://www.eclipse.org/downloads/packages/release/2020-06/r/eclipse-ide-enterprise-java-developers download according to your OS. And after downloading and extracting the ZIP open the extract folder and click on Eclipse application icon.
Then just enter your workspace and get started. Now you will be able to see the servers option in Window->Show View, like this:
If you already have the data "for (Parcelable currentHeadline : allHeadlines)," then why are you doing that in a separate thread?
You should poll the data in a separate thread, and when it's finished gathering it, then call your populateTables method on the UI thread:
private void populateTable() {
runOnUiThread(new Runnable(){
public void run() {
//If there are stories, add them to the table
for (Parcelable currentHeadline : allHeadlines) {
addHeadlineToTable(currentHeadline);
}
try {
dialog.dismiss();
} catch (final Exception ex) {
Log.i("---","Exception in thread");
}
}
});
}
m2e is only included in the Java developer version of Eclipse, as you can see on this page ("Maven" topic): http://www.eclipse.org/downloads/compare.php
However, an easy way to get m2e is through the Eclipse Marketplace:
Go to Help -> Eclipse Marketplace and look for m2e. Click "Maven Integration for Eclipse", then on Install (or drag and drop the install link to your running Eclipse workspace if you opened the marketplace in a browser), et voila!
Direct browser access: http://marketplace.eclipse.org/content/maven-integration-eclipse
thy this:
@UiThread
public void logMsg(final String msg) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Log.d("UI thread", "I am the UI thread");
}
});
}
First of all, don't create HTML elements by string concatenation. Use DOM manipulation. It's faster, cleaner, and less error-prone. This alone solves one of your problems. Then, just let it accept any array as an argument:
var options = [
set0 = ['Option 1','Option 2'],
set1 = ['First Option','Second Option','Third Option']
];
function makeUL(array) {
// Create the list element:
var list = document.createElement('ul');
for (var i = 0; i < array.length; i++) {
// Create the list item:
var item = document.createElement('li');
// Set its contents:
item.appendChild(document.createTextNode(array[i]));
// Add it to the list:
list.appendChild(item);
}
// Finally, return the constructed list:
return list;
}
// Add the contents of options[0] to #foo:
document.getElementById('foo').appendChild(makeUL(options[0]));
Here's a demo. You might also want to note that set0
and set1
are leaking into the global scope; if you meant to create a sort of associative array, you should use an object:
var options = {
set0: ['Option 1', 'Option 2'],
set1: ['First Option', 'Second Option', 'Third Option']
};
And access them like so:
makeUL(options.set0);
As the message says, you have a task which threw an unhandled exception.
Turn on Break on All Exceptions (Debug, Exceptions) and rerun the program.
This will show you the original exception when it was thrown in the first place.
(comment appended): In VS2015 (or above). Select Debug > Options > Debugging > General and unselect the "Enable Just My Code" option.
I had the same problem - my scenario was that I was referencing the new System.Web.Mvc.dll from a lib folder and I did not have "Copy Local" set to true. The application was then reverting back to the version in the GAC which didn't have the correct namespaces (Html, Ajax etc) in it and was giving me the run time error.
Update 10/11/2020 to reflect the latest brew changes.
Brew
already provide a command to uninstall itself (this will remove everything you installed with Homebrew):
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)"
If you failed to run this command due to permission (like run as second user), run again with sudo
Then you can install again:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
The Set
interface does not provide any ordering guarantees.
Its sub-interface SortedSet
represents a set that is sorted according to some criterion. In Java 6, there are two standard containers that implement SortedSet
. They are TreeSet
and ConcurrentSkipListSet
.
In addition to the SortedSet
interface, there is also the LinkedHashSet
class. It remembers the order in which the elements were inserted into the set, and returns its elements in that order.
random.rand
is deprecated meanwhile.This works with matplotlip 3.2.1:
from matplotlib import pyplot as plt
import random
import numpy as np
random = np.random.random ([8,90])
plt.figure(figsize = (20,2))
plt.imshow(random, interpolation='nearest')
This plots:
To change the random number, you can experiment with np.random.normal(0,1,(8,90))
(here mean = 0, standard deviation = 1).
I believe this will do what you are looking for.
.cssClass li {
list-style-type: disc;
list-style-position: inside;
text-indent: -1em;
padding-left: 1em;
}
JSFiddle: https://jsfiddle.net/dzbos70f/
You can use jQuery's .eq()
method to get the element with a certain index.
$('ul li').eq(index).css({'background-color':'#343434'});
This piece of configuration in web.config file can help as helped to me: in the system.webServer section:
<security>
<requestFiltering>
<verbs applyToWebDAV="true">
<remove verb="PUT" />
<add verb="PUT" allowed="true" />
<remove verb="DELETE" />
<add verb="DELETE" allowed="true" />
<remove verb="PATCH" />
<add verb="PATCH" allowed="true" />
</verbs>
</requestFiltering>
</security>
if you do not want to use the collections library, you can always do something like this:
given that a
and b
are your lists, the following returns the number of matching elements (it considers the order).
sum([1 for i,j in zip(a,b) if i==j])
Therefore,
len(a)==len(b) and len(a)==sum([1 for i,j in zip(a,b) if i==j])
will be True
if both lists are the same, contain the same elements and in the same order. False
otherwise.
So, you can define the compare function like the first response above,but without the collections library.
compare = lambda a,b: len(a)==len(b) and len(a)==sum([1 for i,j in zip(a,b) if i==j])
and
>>> compare([1,2,3], [1,2,3,3])
False
>>> compare([1,2,3], [1,2,3])
True
>>> compare([1,2,3], [1,2,4])
False
This code will remove the indentation and list bullets.
ul {
padding: 0;
list-style-type: none;
}
I know I'm a bit late to the party, but if you can put up with having the lines left-justified, one hack is to put the pipes before the items and then put a mask over the left edge, basically like so:
li::before {
content: " | ";
white-space: nowrap;
}
ul, li {
display: inline;
}
.mask {
width:4px;
position: absolute;
top:8px; //position as needed
}
more complete example: http://jsbin.com/hoyaduxi/1/edit
The problem is that the regex pattern is being HTML encoded twice, once when the regex is being built, and once when being rendered in your view.
For now, try wrapping your TextBoxFor in an Html.Raw
, like so:
@Html.Raw(Html.TextBoxFor(model => Model.FirstName, new { }))
You can (A) change the markup to not use paragraphs
<span>Text</span>
<br>
<ul>
<li>One</li>
</ul>
<span>Text 2</span>
Or (B) change the css
p{margin:0px;}
Demos here: http://jsfiddle.net/ZnpVu/1
Font-awesome provides a great solution out of the box:
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" />_x000D_
_x000D_
<ul class='fa-ul'>_x000D_
<li><i class="fa-li fa fa-plus"></i> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam</li>_x000D_
<li><i class="fa-li fa fa-plus"></i> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam</li>_x000D_
</ul>
_x000D_
You can also find a copy of the nuspec.xsd here as it seems to no longer be available:
As noted by others, $('ul').empty()
works fine, as does:
$('ul li').remove();
Alternatively one can use the setExtremes method also,
yAxis.setExtremes(0, 100);
Or if only one value is needed to be set, just leave other as null
yAxis.setExtremes(null, 100);
Try the following (calling clearAllEditTextFocuses();
)
private final boolean clearAllEditTextFocuses() {
View v = getCurrentFocus();
if(v instanceof EditText) {
final FocusedEditTextItems list = new FocusedEditTextItems();
list.addAndClearFocus((EditText) v);
//Focus von allen EditTexten entfernen
boolean repeat = true;
do {
v = getCurrentFocus();
if(v instanceof EditText) {
if(list.containsView(v))
repeat = false;
else list.addAndClearFocus((EditText) v);
} else repeat = false;
} while(repeat);
final boolean result = !(v instanceof EditText);
//Focus wieder setzen
list.reset();
return result;
} else return false;
}
private final static class FocusedEditTextItem {
private final boolean focusable;
private final boolean focusableInTouchMode;
@NonNull
private final EditText editText;
private FocusedEditTextItem(final @NonNull EditText v) {
editText = v;
focusable = v.isFocusable();
focusableInTouchMode = v.isFocusableInTouchMode();
}
private final void clearFocus() {
if(focusable)
editText.setFocusable(false);
if(focusableInTouchMode)
editText.setFocusableInTouchMode(false);
editText.clearFocus();
}
private final void reset() {
if(focusable)
editText.setFocusable(true);
if(focusableInTouchMode)
editText.setFocusableInTouchMode(true);
}
}
private final static class FocusedEditTextItems extends ArrayList<FocusedEditTextItem> {
private final void addAndClearFocus(final @NonNull EditText v) {
final FocusedEditTextItem item = new FocusedEditTextItem(v);
add(item);
item.clearFocus();
}
private final boolean containsView(final @NonNull View v) {
boolean result = false;
for(FocusedEditTextItem item: this) {
if(item.editText == v) {
result = true;
break;
}
}
return result;
}
private final void reset() {
for(FocusedEditTextItem item: this)
item.reset();
}
}
If you are in a virtualenv you need to activate it before you can run ./manage.py 'command'
source path/to/your/virtualenv/bin/activate
if you config workon in .bash_profile or .bashrc
workon yourvirtualenvname
*please dont edit your manage.py file maybe works by isnt the correct way and could give you future errors
This method works best to me:
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
for(var i = this.length - 1; i >= 0; i--) {
if(this[i] && this[i].parentElement) {
this[i].parentElement.removeChild(this[i]);
}
}
}
To use it we can deploy like this:
document.getElementsByID('DIV_Id').remove();
or
document.getElementsByClassName('DIV_Class').remove();
Easy way to parse the xml is to use the LINQ to XML
for example you have the following xml file
<library>
<track id="1" genre="Rap" time="3:24">
<name>Who We Be RMX (feat. 2Pac)</name>
<artist>DMX</artist>
<album>The Dogz Mixtape: Who's Next?!</album>
</track>
<track id="2" genre="Rap" time="5:06">
<name>Angel (ft. Regina Bell)</name>
<artist>DMX</artist>
<album>...And Then There Was X</album>
</track>
<track id="3" genre="Break Beat" time="6:16">
<name>Dreaming Your Dreams</name>
<artist>Hybrid</artist>
<album>Wide Angle</album>
</track>
<track id="4" genre="Break Beat" time="9:38">
<name>Finished Symphony</name>
<artist>Hybrid</artist>
<album>Wide Angle</album>
</track>
<library>
For reading this file, you can use the following code:
public void Read(string fileName)
{
XDocument doc = XDocument.Load(fileName);
foreach (XElement el in doc.Root.Elements())
{
Console.WriteLine("{0} {1}", el.Name, el.Attribute("id").Value);
Console.WriteLine(" Attributes:");
foreach (XAttribute attr in el.Attributes())
Console.WriteLine(" {0}", attr);
Console.WriteLine(" Elements:");
foreach (XElement element in el.Elements())
Console.WriteLine(" {0}: {1}", element.Name, element.Value);
}
}
I think that all the answers missed a crucial point:
If you use the Ajax form so that it needs to update itself (and NOT another div outside of the form) then you need to put the containing div OUTSIDE of the form. For example:
<div id="target">
@using (Ajax.BeginForm("MyAction", "MyController",
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "target"
}))
{
<!-- whatever -->
}
</div>
Otherwise you will end like @David where the result is displayed in a new page.
I had the very same problem today. Here is a simple solution we found to solve this issue (thanks to Anghiara):
Instead of loading your new code to the Arduino using the "upload button" (the circle with the green arrow) in your screen, use your mouse to click "Sketch" and then "Upload".
Please remember to add a delay() line to your code when working with Serial.println() and loops. I learned my lesson the hard way.
Basically you need following things to make location detector android app
Now if you write each of these module yourself then it needs much time and efforts. So it would be better to use ready resources that are being maintained already.
Using all these resources, you will be able to create an flawless android location detection app.
You will first need to listen for current location of user. You can use any of below libraries to quick start.
This library provide last known location, location updates
With this library you just need to provide a Configuration object with your requirements, and you will receive a location or a fail reason with all the stuff are described above handled.
Use this open source repo of the Hypertrack Live app to build live location sharing experience within your app within a few hours. HyperTrack Live app helps you share your Live Location with friends and family through your favorite messaging app when you are on the way to meet up. HyperTrack Live uses HyperTrack APIs and SDKs.
Google Maps Android API utility library
If you want to add route maps feature in your apps you can use DrawRouteMaps to make you work more easier. This is lib will help you to draw route maps between two point LatLng.
Simple, smooth animation for route / polylines on google maps using projections. (WIP)
This project allows you to calculate the direction between two locations and display the route on a Google Map using the Google Directions API.
I needed a more flexible solution for working on multiple git repositories so I wrote the following sh code based on 1 and 2. You can use your server address instead of gitlab.com and your port in replace of 22.
SERVER=gitlab.com
PORT=22
nc -z -v -w5 $SERVER $PORT
result1=$?
#Do whatever you want
if [ "$result1" != 0 ]; then
echo 'port 22 is closed'
else
echo 'port 22 is open'
fi
I had the same issues but nothing worked. What I did was I added this to the selector:
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
As to why, no idea.
A reset will most certainly fix this:
ul { margin: 0; padding: 0; }
Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).
You need to do a deep equals.
From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.
Object.extend(Object, {
deepEquals: function(o1, o2) {
var k1 = Object.keys(o1).sort();
var k2 = Object.keys(o2).sort();
if (k1.length != k2.length) return false;
return k1.zip(k2, function(keyPair) {
if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
} else {
return o1[keyPair[0]] == o2[keyPair[1]];
}
}).all();
}
});
Usage:
var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);
if (Object.deepEquals(anObj, anotherObj))
...
As recommended by official documentation, you can use AsyncTask to handle work items shorter than 5ms in duration. If your task take more time, lookout for other alternatives.
HandlerThread is one alternative to Thread
or AsyncTask
. If you need to update UI from HandlerThread
, post a message on UI Thread Looper
and UI Thread Handler can handle UI updates.
Example code:
You are mixing the 2 different CASE
syntaxes inappropriately.
Use this style (Searched)
CASE
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Or this style (Simple)
CASE u.nnmu
WHEN '0' THEN mu.naziv_mesta
WHEN '1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Not This (Simple but with boolean search predicates)
CASE u.nnmu
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
In MySQL this will end up testing whether u.nnmu
is equal to the value of the boolean expression u.nnmu ='0'
itself. Regardless of whether u.nnmu
is 1
or 0
the result of the case expression itself will be 1
For example if nmu = '0'
then (nnmu ='0'
) evaluates as true
(1) and (nnmu ='1'
) evaluates as false
(0). Substituting these into the case expression gives
SELECT CASE '0'
WHEN 1 THEN '0'
WHEN 0 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
if nmu = '1'
then (nnmu ='0'
) evaluates as false
(0) and (nnmu ='1'
) evaluates as true
(1). Substituting these into the case expression gives
SELECT CASE '1'
WHEN 0 THEN '0'
WHEN 1 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
I was running into the same issue and wanted to avoid adding the intent filter as you described. After some digging, I found an xml attribute android:exported that you should add to the activity you would like to be called.
It is by default set to false if no intent filter added to your activity, but if you do have an intent filter it gets set to true.
here is the documentation http://developer.android.com/guide/topics/manifest/activity-element.html#exported
tl;dr: addandroid:exported="true"
to your activity in your AndroidManifest.xml file and avoid adding the intent-filter :)
There is no "second property" -- when you say var obj = { ... }
, the properties inside the braces are unordered. Even a 'for' loop walking through them might return them in different orders on different JavaScript implementations.
Actually...
To hide an absolute positioned element, the container position
must be anything except for static
. It can be relative
or fixed
in addition to absolute
.
Note Slipstream's response, that base64.b64encode
and base64.b64decode
need bytes-like object, not string.
>>> import base64
>>> a = '{"name": "John", "age": 42}'
>>> base64.b64encode(a)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/lib/python3.6/base64.py", line 58, in b64encode
encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'
I found a module written by Brett Alistair Kromkamp which was not completed. I finished it and make it public on github and renamed it as treelib
(original pyTree
):
https://github.com/caesar0301/treelib
May it help you....
Presuming 17px header height
List css:
height: 100%;
padding-top: 17px;
Header css:
height: 17px;
float: left;
width: 100%;
I was intrigued by the answer from @Jerry Coffin, which suggested that the ordered map would exhibit performance increases on long strings, after some experimentation (which can be downloaded from pastebin), I've found that this seems to hold true only for collections of random strings, when the map is initialised with a sorted dictionary (which contain words with considerable amounts of prefix-overlap), this rule breaks down, presumably because of the increased tree depth necessary to retrieve value. The results are shown below, the 1st number column is insert time, 2nd is fetch time.
g++ -g -O3 --std=c++0x -c -o stdtests.o stdtests.cpp
g++ -o stdtests stdtests.o
gmurphy@interloper:HashTests$ ./stdtests
# 1st number column is insert time, 2nd is fetch time
** Integer Keys **
unordered: 137 15
ordered: 168 81
** Random String Keys **
unordered: 55 50
ordered: 33 31
** Real Words Keys **
unordered: 278 76
ordered: 516 298
This approach can be tried if you don't want to use any library and keep it simple and short!
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
marked = []
b = [(a.count(i), marked.append(i))[0] for i in a if i not in marked]
print(b)
o/p
[4, 4, 2, 1, 2]
You can try something like this:
class mylist(list):
def __sub__(self, b):
result = self[:]
b = b[:]
while b:
try:
result.remove(b.pop())
except ValueError:
raise Exception("Not all elements found during subtraction")
return result
a = mylist([0, 1, 2, 1, 0] )
b = mylist([0, 1, 1])
>>> a - b
[2, 0]
You have to define what [1, 2, 3] - [5, 6] should output though, I guess you want [1, 2, 3] thats why I ignore the ValueError.
Edit:
Now I see you wanted an exception if a
does not contain all elements, added it instead of passing the ValueError.
The fastest method I've tried so far is based on the Python cookbook erat2
function:
import itertools as it
def erat2a( ):
D = { }
yield 2
for q in it.islice(it.count(3), 0, None, 2):
p = D.pop(q, None)
if p is None:
D[q*q] = q
yield q
else:
x = q + 2*p
while x in D:
x += 2*p
D[x] = p
See this answer for an explanation of the speeding-up.
Although this is a pretty old question I must say it is touching exactly the knowledge I was missing during my first steps in R - i.e. how to express data in my hand as an object in R or how to select from existing objects. It is not easy for an R novice to think "in an R box" from the very beginning.
So I myself started to use crutches below which helped me a lot to find out what object to use for what data, and basically to imagine real-world usage.
Though I not giving exact answers to the question the short text below might help the reader who just started with R and is asking similar questions.
[
subsets.[
subsets.[
subsets by rows and columns, or by sequence.list
where I can subset using [
by rows and columns, but even using [[
.tree structure
where [i]
selects and returns whole branches and [[i]]
returns item from the branch. And because it is tree like structure
, you can even use an index sequence
to address every single leaf on a very complex list
using its [[index_vector]]
. Lists can be simple or very complex and can mix together various types of objects into one.So for lists
you can end up with more ways how to select a leaf
depending on situation like in the following example.
l <- list("aaa",5,list(1:3),LETTERS[1:4],matrix(1:9,3,3))
l[[c(5,4)]] # selects 4 from matrix using [[index_vector]] in list
l[[5]][4] # selects 4 from matrix using sequential index in matrix
l[[5]][1,2] # selects 4 from matrix using row and column in matrix
This way of thinking helped me a lot.
Retrieve informations from image elements on the page
Test working on Chrome and Firefox
Working jsFiddle (open your console to see the result)
$('img').each(function(){ // selecting all image element on the page
var img = new Image($(this)); // creating image element
img.onload = function() { // trigger if the image was loaded
console.log($(this).attr('src') + ' - done!');
}
img.onerror = function() { // trigger if the image wasn't loaded
console.log($(this).attr('src') + ' - error!');
}
img.onAbort = function() { // trigger if the image load was abort
console.log($(this).attr('src') + ' - abort!');
}
img.src = $(this).attr('src'); // pass src to image object
// log image attributes
console.log(img.src);
console.log(img.width);
console.log(img.height);
console.log(img.complete);
});
Note : I used jQuery, I thought this can be acheive on full javascript
I find good information here OpenClassRoom --> this is a French forum
It might be worth noting that this can also occur when Windows blocks downloads that it considers to be unsafe. This can be addressed by right-clicking the jar file (such as ojdbc7.jar), and checking the 'Unblock' box at the bottom.
Windows JAR File Properties Dialog:
Try wrapping the list in a div and give that div the inline property instead of your list.
Well... These are PHP. There is an sms one from google here.
And github has one here.
Another sms one is here. However, this one has a lot more code, so it may take up more space.
COALESCE(field, 'default')
For example:
SELECT
t.id,
COALESCE(d.field, 'default')
FROM
test t
LEFT JOIN
detail d ON t.id = d.item
Also, you can use multiple columns to check their NULL
by COALESCE function.
For example:
mysql> SELECT COALESCE(NULL, 1, NULL);
-> 1
mysql> SELECT COALESCE(0, 1, NULL);
-> 0
mysql> SELECT COALESCE(NULL, NULL, NULL);
-> NULL
If you are using ASP.NET MVC – you do not need an additional HTTP handler and some modifications of the web.config file. All you need – just to add some simple action in a Home/Common controller:
[HttpPost]
public JsonResult KeepSessionAlive() {
return new JsonResult {Data = "Success"};
}
, write a piece of JavaScript code like this one (I have put it in one of site’s JavaScript file):
var keepSessionAlive = false;
var keepSessionAliveUrl = null;
function SetupSessionUpdater(actionUrl) {
keepSessionAliveUrl = actionUrl;
var container = $("#body");
container.mousemove(function () { keepSessionAlive = true; });
container.keydown(function () { keepSessionAlive = true; });
CheckToKeepSessionAlive();
}
function CheckToKeepSessionAlive() {
setTimeout("KeepSessionAlive()", 5*60*1000);
}
function KeepSessionAlive() {
if (keepSessionAlive && keepSessionAliveUrl != null) {
$.ajax({
type: "POST",
url: keepSessionAliveUrl,
success: function () { keepSessionAlive = false; }
});
}
CheckToKeepSessionAlive();
}
, and initialize this functionality by calling a JavaScript function:
SetupSessionUpdater('/Home/KeepSessionAlive');
Please note! I have implemented this functionality only for authorized users (there is no reason to keep session state for guests in most cases) and decision to keep session state active is not only based on – is browser open or not, but authorized user must do some activity on the site (move a mouse or type some key).
Just to add to this thread - if you are moving an existing item you will need to use clone
and then true/false on whether you clone/deep-clone the events as well (https://api.jquery.com/clone/).
Example:
$("#content ul").append($('.existing_li').clone(true));
in the folder where the build.xml resides run command only -
ant
and not the command - `
ant build.xml
`
. if you are using the ant file as build xml then the below steps helps you Steps : open cmd Prompt >> switch to the project location >>type ant and click enter key
Update: As of 2013 the two I've seen that are worth checking are:
Yeah!
As of 2012 one of the most lightweight, flexible solutions I've found is ddSlick. Relevant (edited) info from the site:
select options
And here's a preview of the various modes:
Try this JavaScript code:
function printout() {
var newWindow = window.open();
newWindow.document.write(document.getElementById("output").innerHTML);
newWindow.print();
}
<div class="custom-control custom-checkbox left">
<ul class="list-unstyled">
<li>
<label class="btn btn-secondary text-left" style="width:100%;text-align:left;padding:2px;">
<input type="checkbox" style="zoom:1.7;vertical-align:bottom;" asp-for="@Model[i].IsChecked" class="custom-control-input" /> @Model[i].Title
</label>
</li>
</ul>
</div>
Most of Scala's logging libraries have been some wrappers around a Java logging framework (slf4j, log4j etc), but as of March 2015, the surviving log libraries are all slf4j. These log libraries provide some sort of log
object to which you can call info(...)
, debug(...)
, etc. I'm not a big fan of slf4j, but it now seems to be the predominant logging framework. Here's the description of SLF4J:
The Simple Logging Facade for Java or (SLF4J) serves as a simple facade or abstraction for various logging frameworks, e.g. java.util.logging, log4j and logback, allowing the end user to plug in the desired logging framework at deployment time.
The ability to change underlying log library at deployment time brings in unique characteristic to the entire slf4j family of loggers, which you need to be aware of:
In a large project, it could actually be convenient to be able to control the logging behavior of transitive dependencies if everyone used slf4j.
Scala Logging is written by Heiko Seeberger as a successor to his slf4s. It uses macro to expand calls into if expression to avoid potentially expensive log call.
Scala Logging is a convenient and performant logging library wrapping logging libraries like SLF4J and potentially others.
I don't know why the first answer is the best one, I tried it and not working in fact, as @kalys.osmonov said, you can give text-align:center
to header
, but you have to make ul
as inline-block
rather than inline
, and also you have to notice that text-align
can be inherited which is not good to some degree, so the better way (not working below IE 9) is using margin
and transform
. Just remove float right
and margin;0 auto
from ul
, like below:
#header ul {
/* float: right; */
/* margin: 0 auto; */
display: inline-block;
margin-left: 50%; /* From parent width */
transform: translateX(-50%); /* use self width which can be unknown */
-ms-transform: translateX(-50%); /* For IE9 */
}
This way can fix the problem that making dynamic width of ul
center if you don't care IE8 etc.
For Linux & Unix System you can use ps -ef | grep process_name
to get the full command line.
On SunOS systems, if you want to get full command line, you can use
/usr/ucb/ps -auxww | grep -i process_name
To get the full command line you need to become super user.
pargs -a PROCESS_ID
will give a detailed list of arguments passed to a process. It will output the array of arguments in like this:
argv[o]: first argument
argv[1]: second..
argv[*]: and so on..
I didn't find any similar command for Linux, but I would use the following command to get similar output:
tr '\0' '\n' < /proc/<pid>/environ
If you can, a better choice may be to change the function to take either an iterator to an element or a brand new vector (if it does not modify).
While you can do this sort of things with arrays since you know how they are stored, it's probably a bad idea to do the same with vectors. &foo[1]
does not have the type vector<int>*
.
Also, while the STL implementation is available online, it's usually risky to try and rely on the internal structure of an abstraction.
You can use Object.keys(), "which returns an array of a given object's own enumerable property names, in the same order as we get with a normal loop."
You can use any object in place of stats
:
var stats = {_x000D_
a: 3,_x000D_
b: 6,_x000D_
d: 7,_x000D_
erijgolekngo: 35_x000D_
}_x000D_
/* this is the answer here */_x000D_
for (var key in Object.keys(stats)) {_x000D_
var t = Object.keys(stats)[key];_x000D_
console.log(t + " value =: " + stats[t]);_x000D_
}
_x000D_
A web site for coloration with lots of languages. http://hilite.me/
You can host one yourself since it is open source. The code is on github.
In an ideal world you'd achieve this simply using the following css
<style type="text/css">
span {
display: inline-block;
width: 50px;
}
</style>
This works on all browsers apart from FF2 and below.
Firefox 2 and lower don't support this value. You can use -moz-inline-box, but be aware that it's not the same as inline-block, and it may not work as you expect in some situations.
Quote taken from quirksmode
There's a tool called JODConverter which hooks into open office to expose it's file format converters, there's versions available as a webapp (sits in tomcat) which you post to and a command line tool. I've been firing html at it and converting to .doc and pdf succesfully it's in a fairly big project, haven't gone live yet but I think I'm going to be using it. http://sourceforge.net/projects/jodconverter/
Try it:
#!/usr/bin/python
import gtk.gdk
import time
import random
import socket
import fcntl
import struct
import getpass
import os
import paramiko
while 1:
# generate a random time between 120 and 300 sec
random_time = random.randrange(20,25)
# wait between 120 and 300 seconds (or between 2 and 5 minutes)
print "Next picture in: %.2f minutes" % (float(random_time) / 60)
time.sleep(random_time)
w = gtk.gdk.get_default_root_window()
sz = w.get_size()
print "The size of the window is %d x %d" % sz
pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])
ts = time.asctime( time.localtime(time.time()) )
date = time.strftime("%d-%m-%Y")
timer = time.strftime("%I:%M:%S%p")
filename = timer
filename += ".png"
if (pb != None):
username = getpass.getuser() #Get username
newpath = r'screenshots/'+username+'/'+date #screenshot save path
if not os.path.exists(newpath): os.makedirs(newpath)
saveas = os.path.join(newpath,filename)
print saveas
pb.save(saveas,"png")
else:
print "Unable to get the screenshot."
Thanks WChoward for your answer. I expanded:
.nav-link, .dropdown-item {
color: blue !important;
}
.nav-link:hover, .dropdown-item:hover {
color: darkgreen !important;
}
Working for me with this line (simply add --listen when running) :
node server.js -p 3000 -a : --listen 192.168.1.100
Hope it helps...
You could find this fiddle useful. Just finished. https://jsfiddle.net/dnviti/ogpt920w/ Code below also:
/** _x000D_
* Get the ISO week date week number _x000D_
*/ _x000D_
Date.prototype.getWeek = function () { _x000D_
// Create a copy of this date object _x000D_
var target = new Date(this.valueOf()); _x000D_
_x000D_
// ISO week date weeks start on monday _x000D_
// so correct the day number _x000D_
var dayNr = (this.getDay() + 6) % 7; _x000D_
_x000D_
// ISO 8601 states that week 1 is the week _x000D_
// with the first thursday of that year. _x000D_
// Set the target date to the thursday in the target week _x000D_
target.setDate(target.getDate() - dayNr + 3); _x000D_
_x000D_
// Store the millisecond value of the target date _x000D_
var firstThursday = target.valueOf(); _x000D_
_x000D_
// Set the target to the first thursday of the year _x000D_
// First set the target to january first _x000D_
target.setMonth(0, 1); _x000D_
// Not a thursday? Correct the date to the next thursday _x000D_
if (target.getDay() != 4) { _x000D_
target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7); _x000D_
} _x000D_
_x000D_
// The weeknumber is the number of weeks between the _x000D_
// first thursday of the year and the thursday in the target week _x000D_
return 1 + Math.ceil((firstThursday - target) / 604800000); // 604800000 = 7 * 24 * 3600 * 1000 _x000D_
} _x000D_
_x000D_
/** _x000D_
* Get the ISO week date year number _x000D_
*/ _x000D_
Date.prototype.getWeekYear = function () _x000D_
{ _x000D_
// Create a new date object for the thursday of this week _x000D_
var target = new Date(this.valueOf()); _x000D_
target.setDate(target.getDate() - ((this.getDay() + 6) % 7) + 3); _x000D_
_x000D_
return target.getFullYear(); _x000D_
}_x000D_
_x000D_
/** _x000D_
* Convert ISO week number and year into date (first day of week)_x000D_
*/ _x000D_
var getDateFromISOWeek = function(w, y) {_x000D_
var simple = new Date(y, 0, 1 + (w - 1) * 7);_x000D_
var dow = simple.getDay();_x000D_
var ISOweekStart = simple;_x000D_
if (dow <= 4)_x000D_
ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1);_x000D_
else_x000D_
ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay());_x000D_
return ISOweekStart;_x000D_
}_x000D_
_x000D_
var printDate = function(){_x000D_
/*var dateString = document.getElementById("date").value;_x000D_
var dateArray = dateString.split("/");*/ // use this if you have year-week in the same field_x000D_
_x000D_
var dateInput = document.getElementById("date").value;_x000D_
if (dateInput == ""){_x000D_
var date = new Date(); // get today date object_x000D_
}_x000D_
else{_x000D_
var date = new Date(dateInput); // get date from field_x000D_
}_x000D_
_x000D_
var day = ("0" + date.getDate()).slice(-2); // get today day_x000D_
var month = ("0" + (date.getMonth() + 1)).slice(-2); // get today month_x000D_
var fullDate = date.getFullYear()+"-"+(month)+"-"+(day) ; // get full date_x000D_
var year = date.getFullYear();_x000D_
var week = ("0" + (date.getWeek())).slice(-2);_x000D_
var locale= "it-it";_x000D_
_x000D_
document.getElementById("date").value = fullDate; // set input field_x000D_
_x000D_
document.getElementById("year").value = year;_x000D_
document.getElementById("week").value = week; // this prototype has been written above_x000D_
_x000D_
var fromISODate = getDateFromISOWeek(week, year);_x000D_
_x000D_
var fromISODay = ("0" + fromISODate.getDate()).slice(-2);_x000D_
var fromISOMonth = ("0" + (fromISODate.getMonth() + 1)).slice(-2);_x000D_
var fromISOYear = date.getFullYear();_x000D_
_x000D_
// Use long to return month like "December" or short for "Dec"_x000D_
//var monthComplete = fullDate.toLocaleString(locale, { month: "long" }); _x000D_
_x000D_
var formattedDate = fromISODay + "-" + fromISOMonth + "-" + fromISOYear;_x000D_
_x000D_
var element = document.getElementById("fullDate");_x000D_
_x000D_
element.value = formattedDate;_x000D_
}_x000D_
_x000D_
printDate();_x000D_
document.getElementById("convertToDate").addEventListener("click", printDate);
_x000D_
*{_x000D_
font-family: consolas_x000D_
}
_x000D_
<label for="date">Date</label>_x000D_
<input type="date" name="date" id="date" style="width:130px;text-align:center" value="" />_x000D_
<br /><br />_x000D_
<label for="year">Year</label>_x000D_
<input type="year" name="year" id="year" style="width:40px;text-align:center" value="" />_x000D_
-_x000D_
<label for="week">Week</label>_x000D_
<input type="text" id="week" style="width:25px;text-align:center" value="" />_x000D_
<br /><br />_x000D_
<label for="fullDate">Full Date</label>_x000D_
<input type="text" id="fullDate" name="fullDate" style="width:80px;text-align:center" value="" />_x000D_
<br /><br />_x000D_
<button id="convertToDate">_x000D_
Convert Date_x000D_
</button>
_x000D_
It's pure JS. There are a bunch of date functions inside that allow you to convert date into week number and viceversa :)
You can use UNION in this case
select id, name, games, goals from tblMadrid
union
select id, name, games, goals from tblBarcelona
you jsut have to maintain order of selected columns ie id, name, games, goals in both SQLs
From the numpy.polyfit documentation, it is fitting linear regression. Specifically, numpy.polyfit with degree 'd' fits a linear regression with the mean function
E(y|x) = p_d * x**d + p_{d-1} * x **(d-1) + ... + p_1 * x + p_0
So you just need to calculate the R-squared for that fit. The wikipedia page on linear regression gives full details. You are interested in R^2 which you can calculate in a couple of ways, the easisest probably being
SST = Sum(i=1..n) (y_i - y_bar)^2
SSReg = Sum(i=1..n) (y_ihat - y_bar)^2
Rsquared = SSReg/SST
Where I use 'y_bar' for the mean of the y's, and 'y_ihat' to be the fit value for each point.
I'm not terribly familiar with numpy (I usually work in R), so there is probably a tidier way to calculate your R-squared, but the following should be correct
import numpy
# Polynomial Regression
def polyfit(x, y, degree):
results = {}
coeffs = numpy.polyfit(x, y, degree)
# Polynomial Coefficients
results['polynomial'] = coeffs.tolist()
# r-squared
p = numpy.poly1d(coeffs)
# fit values, and mean
yhat = p(x) # or [p(z) for z in x]
ybar = numpy.sum(y)/len(y) # or sum(y)/len(y)
ssreg = numpy.sum((yhat-ybar)**2) # or sum([ (yihat - ybar)**2 for yihat in yhat])
sstot = numpy.sum((y - ybar)**2) # or sum([ (yi - ybar)**2 for yi in y])
results['determination'] = ssreg / sstot
return results
The best way could be to save all the emails in a database.
You can try this code, assuming you have your email in a database
/*Your connection to your database comes here*/
$query="select email from yourtable";
$result =mysql_query($query);
/the above code depends on where you saved your email addresses, so make sure you replace it with your parameters/
Then you can make a comma separated string from the result,
while($row=$result->fetch_array()){
if($rows=='') //this prevents from inserting comma on before the first element
$rows.=$row['email'];
else
$rows.=','.$row['email'];
}
Now you can use
$to = explode(',',$rows); // to change to array
$string =implode(',',$cc); //to get back the string separated by comma
With above code you can send the email like this
mail($string, "Test", "Hi, Happy X-Mas and New Year");
I realize this is answered, but there is another option when you're dealing with objects.
If you have an object that might be:
{
name: {
first: "John",
last: "Doe"
}
}
You can use:
obj.get(property_name, value_if_null)
Like:
obj.get("name", {}).get("first", "Name is missing")
By adding {}
as the default value, if "name" is missing, an empty object is returned and passed through to the next get. This is similar to null-safe-navigation in C#, which would be like obj?.name?.first
.
Check out the ColumnComparator. It is basically the same solution as proposed by Costi, but it also supports sorting on columns in a List and has a few more sort properties.
I found a solution for my problem while writing my question !
Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)
I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)
So it seems the problem comes from the use of RDP (windows7 and 8)
Update 2017: Problem occurs on Windows 10 aswell.
You can use down-stepping to achieve better results. Most browsers seem to use linear interpolation rather than bi-cubic when resizing images.
(Update There has been added a quality property to the specs, imageSmoothingQuality
which is currently available in Chrome only.)
Unless one chooses no smoothing or nearest neighbor the browser will always interpolate the image after down-scaling it as this function as a low-pass filter to avoid aliasing.
Bi-linear uses 2x2 pixels to do the interpolation while bi-cubic uses 4x4 so by doing it in steps you can get close to bi-cubic result while using bi-linear interpolation as seen in the resulting images.
var canvas = document.getElementById("canvas");_x000D_
var ctx = canvas.getContext("2d");_x000D_
var img = new Image();_x000D_
_x000D_
img.onload = function () {_x000D_
_x000D_
// set size proportional to image_x000D_
canvas.height = canvas.width * (img.height / img.width);_x000D_
_x000D_
// step 1 - resize to 50%_x000D_
var oc = document.createElement('canvas'),_x000D_
octx = oc.getContext('2d');_x000D_
_x000D_
oc.width = img.width * 0.5;_x000D_
oc.height = img.height * 0.5;_x000D_
octx.drawImage(img, 0, 0, oc.width, oc.height);_x000D_
_x000D_
// step 2_x000D_
octx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5);_x000D_
_x000D_
// step 3, resize to final size_x000D_
ctx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5,_x000D_
0, 0, canvas.width, canvas.height);_x000D_
}_x000D_
img.src = "//i.imgur.com/SHo6Fub.jpg";
_x000D_
<img src="//i.imgur.com/SHo6Fub.jpg" width="300" height="234">_x000D_
<canvas id="canvas" width=300></canvas>
_x000D_
Depending on how drastic your resize is you can might skip step 2 if the difference is less.
In the demo you can see the new result is now much similar to the image element.
This is big endian test from a configure script:
#include <inttypes.h>
int main(int argc, char ** argv){
volatile uint32_t i=0x01234567;
// return 0 for big endian, 1 for little endian.
return (*((uint8_t*)(&i))) == 0x67;
}
Probably you need to set library reference as "Copy Local = True" on properties dialog. On visual studio click on "references" then right-click on the missing reference, from the context menu click properties, you should see copy local setting.
I was facing this issue when cloning data (via HTTP) from remote git repo hosted on AWS EC2 instance managed by elastic beanstalk. The cloning itself was also done on AWS EC2 instance.
I tried all aforementioned solutions and their combinations:
http.postBuffer
http.maxrequestbuffer
git clone
and then git fetch --unshallow
- see fatal: early EOF fatal: index-pack failedpackedGitLimit
et al, see here: fatal: early EOF fatal: index-pack failedclient_max_body_size
to both big value and 0 (unlimited); setting proxy_request_buffering off;
options single-request
in /etc/resolv.confgit clone
After all of this, I was still facing the same issue over and over again, until I found that issue is in Elastic Load Balancer (ELB) cutting the connection. After accessing the EC2 instance (the one hosting git repo) directly instead of going through ELB I've finally managed to clone git repo! I'm still not sure which of ELB (timeout) parameters is responsible for this, so I still have to do some research.
UPDATE
It seems that changing Connection Draining policy for AWS Elastic Load Balancer by raising timeout from 20 seconds to 300 seconds resolved this issue for us.
The relation between the git clone
errors and "connection draining" is strange and not obvious to us. It might be that connection draining timeout change caused some internal changes in ELB configuration that fixed the issue with premature connection closing.
This is the related question on AWS forum (no answer yet): https://forums.aws.amazon.com/thread.jspa?threadID=258572
This is actually more efficient and has better readability in my opinion if you want to access your select with this or another variable
$('#select').find('option:selected')
In fact if I remember correctly phpStorm will attempt to auto correct the other method.
See an example here: http://www.cplusplus.com/reference/stl/vector/insert/ eg.:
...
vector::iterator iterator1;
iterator1= vec1.begin();
vec1.insert ( iterator1+i , vec2[i] );
// This means that at position "i" from the beginning it will insert the value from vec2 from position i
Your first approach was replacing the values from vec1[i] with the values from vec2[i]
I would use vbscript (Windows Scripting Host), because in batch I'm sure you cannot tell that a name is a file or a directory.
In vbs, it can be something like this:
Dim fileSystemObject
Set fileSystemObject = CreateObject("Scripting.FileSystemObject")
Dim mainFolder
Set mainFolder = fileSystemObject.GetFolder(myFolder)
Dim files
Set files = mainFolder.Files
For Each file in files
...
Next
Dim subFolders
Set subFolders = mainFolder.SubFolders
For Each folder in subFolders
...
Next
Check FileSystemObject on MSDN.
This is not obscure, it's the C++ initialization list syntax
Basically, in your case, x
will be initialized with _x
, y
with _y
, z
with _z
.
string newString = url.Substring(18, (url.LastIndexOf(".") - 18))
There is a workaround which may help. You may "register" results for each set_fact iteration and then map that results to list:
---
- hosts: localhost
tasks:
- name: set fact
set_fact: foo_item="{{ item }}"
with_items:
- four
- five
- six
register: foo_result
- name: make a list
set_fact: foo="{{ foo_result.results | map(attribute='ansible_facts.foo_item') | list }}"
- debug: var=foo
Output:
< TASK: debug var=foo >
---------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
ok: [localhost] => {
"var": {
"foo": [
"four",
"five",
"six"
]
}
}
I ran across this error when i ran cordova build android
I solved this issue by firing ./sdkmanager --licenses and accepting all the licenses.
These steps are working on CentOS 6.5 so they should work on CentOS 7 too:
(EDIT - exactly the same steps work for MariaDB 10.3 on CentOS 8)
yum remove mariadb mariadb-server
rm -rf /var/lib/mysql
If your datadir in /etc/my.cnf points to a different directory, remove that directory instead of /var/lib/mysqlrm /etc/my.cnf
the file might have already been deleted at step 1rm ~/.my.cnf
yum install mariadb mariadb-server
[EDIT] - Update for MariaDB 10.1 on CentOS 7
The steps above worked for CentOS 6.5 and MariaDB 10.
I've just installed MariaDB 10.1 on CentOS 7 and some of the steps are slightly different.
Step 1 would become:
yum remove MariaDB-server MariaDB-client
Step 5 would become:
yum install MariaDB-server MariaDB-client
The other steps remain the same.
<form onSubmit="return captureForm()">
that should do. Make sure that your captureForm()
method returns false
.
Probably a more appropriate way of changing outline color is using the outline-color
CSS rule.
textarea {
outline-color: #719ECE;
}
or for input
input {
outline-color: #719ECE;
}
box-shadow
isn't quite the same thing and it may look different than the outline, especially if you apply custom styling to your element.
Angularjs ui bootstrap you can use angularjs ui bootstrap, it provides date validation also
<input type="text" class="form-control"
datepicker-popup="{{format}}" ng-model="dt" is-open="opened"
min-date="minDate" max-date="'2015-06-22'" datepickeroptions="dateOptions"
date-disabled="disabled(date, mode)" ng-required="true">
in controller can specify whatever format you want to display the date as datefilter
$scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
Try starting with the Percona wizard and comparing their recommendations against your current settings one by one. Don't worry there aren't as many applicable settings as you might think.
https://tools.percona.com/wizard
Update circa 2020: Sorry, this tool reached it's end of life: https://www.percona.com/blog/2019/04/22/end-of-life-query-analyzer-and-mysql-configuration-generator/
Everyone points to key_buffer_size
first which you have addressed. With 96GB memory I'd be wary of any tiny default value (likely to be only 96M!).
Inspired by the following resources:
Create and use a @Repeat
annotation as follows:
public class MyTestClass {
@Rule
public RepeatRule repeatRule = new RepeatRule();
@Test
@Repeat(10)
public void testMyCode() {
//your test code goes here
}
}
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention( RetentionPolicy.RUNTIME )
@Target({ METHOD, ANNOTATION_TYPE })
public @interface Repeat {
int value() default 1;
}
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
public class RepeatRule implements TestRule {
private static class RepeatStatement extends Statement {
private final Statement statement;
private final int repeat;
public RepeatStatement(Statement statement, int repeat) {
this.statement = statement;
this.repeat = repeat;
}
@Override
public void evaluate() throws Throwable {
for (int i = 0; i < repeat; i++) {
statement.evaluate();
}
}
}
@Override
public Statement apply(Statement statement, Description description) {
Statement result = statement;
Repeat repeat = description.getAnnotation(Repeat.class);
if (repeat != null) {
int times = repeat.value();
result = new RepeatStatement(statement, times);
}
return result;
}
}
Using this solution with @RunWith(PowerMockRunner.class)
, requires updating to Powermock 1.6.5 (which includes a patch).
If you're using a variable when searching in a string, mysql_real_escape_string()
is good for you. Just my suggestion:
$char = "and way's 'hihi'";
$myvar = mysql_real_escape_string($char);
select * from tablename where fields like "%string $myvar %";
It is possible to play a local video file.
<input type="file" accept="video/*"/>
<video controls autoplay></video>
When a file is selected via the input
element:
input.files
FileListvideo.src
propertyLean back and watch :)
http://jsfiddle.net/dsbonev/cCCZ2/embedded/result,js,html,css/
(function localFileVideoPlayer() {_x000D_
'use strict'_x000D_
var URL = window.URL || window.webkitURL_x000D_
var displayMessage = function(message, isError) {_x000D_
var element = document.querySelector('#message')_x000D_
element.innerHTML = message_x000D_
element.className = isError ? 'error' : 'info'_x000D_
}_x000D_
var playSelectedFile = function(event) {_x000D_
var file = this.files[0]_x000D_
var type = file.type_x000D_
var videoNode = document.querySelector('video')_x000D_
var canPlay = videoNode.canPlayType(type)_x000D_
if (canPlay === '') canPlay = 'no'_x000D_
var message = 'Can play type "' + type + '": ' + canPlay_x000D_
var isError = canPlay === 'no'_x000D_
displayMessage(message, isError)_x000D_
_x000D_
if (isError) {_x000D_
return_x000D_
}_x000D_
_x000D_
var fileURL = URL.createObjectURL(file)_x000D_
videoNode.src = fileURL_x000D_
}_x000D_
var inputNode = document.querySelector('input')_x000D_
inputNode.addEventListener('change', playSelectedFile, false)_x000D_
})()
_x000D_
video,_x000D_
input {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
input {_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
.info {_x000D_
background-color: aqua;_x000D_
}_x000D_
_x000D_
.error {_x000D_
background-color: red;_x000D_
color: white;_x000D_
}
_x000D_
<h1>HTML5 local video file player example</h1>_x000D_
<div id="message"></div>_x000D_
<input type="file" accept="video/*" />_x000D_
<video controls autoplay></video>
_x000D_
If you are after performance and not precision, you should note that calculations with floats are much faster than decimals
Use prop
$(".checkBoxClass").prop('checked', true);
or to uncheck:
$(".checkBoxClass").prop('checked', false);
$("#ckbCheckAll").click(function () {
$(".checkBoxClass").prop('checked', $(this).prop('checked'));
});
Updated JSFiddle Link: http://jsfiddle.net/sVQwA/1/
You can avoid std::bind
doing this:
std::function<void(void)> f = [this]-> {Foo::doSomething();}
How can you tell string
is a reference type? I'm not sure that it matters how it is implemented. Strings in C# are immutable precisely so that you don't have to worry about this issue.
You must turn off "background refresh" for all queries. If background refresh is on, Excel works ahead while the refresh occurs and you have problems.
Data > Connections > Properties > (uncheck) enable background refresh
<Switch
android:thumb="@drawable/thumb"
android:track="@drawable/track"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
I like to give explain here, with suitable example.
Consider a case here..
int totalValue = MySession.ListCustomerAccounts()
.FindAll(ac => ac.AccountHead.AccountHeadID
== accountHead.AccountHeadID)
.Sum(account => account.AccountValue);
Here Consider the functions I am using ..
1. ListCustomerAccounts() // User Defined
2. FindAll() // Pre-defined Library Function
I can easily use ListCustomerAccount
and FindAll
instead of.,
int totalValue = 0;
List<CustomerAccounts> custAccounts = ListCustomerAccounts();
if(custAccounts !=null ){
List<CustomerAccounts> custAccountsFiltered =
custAccounts.FindAll(ac => ac.AccountHead.AccountHeadID
== accountHead.AccountHeadID );
if(custAccountsFiltered != null)
totalValue = custAccountsFiltered.Sum(account =>
account.AccountValue).ToString();
}
NOTE : Since AccountValue is not null
, the Sum() function will not
return null
., Hence I can use it directly.
I did mine with EF 6.x like this:
using(var db = new ProFormDbContext())
{
var Action = 1;
var xNTID = "A239333";
var userPlan = db.Database.SqlQuery<UserPlan>(
"AD.usp_UserPlanInfo @Action, @NTID", //, @HPID",
new SqlParameter("Action", Action),
new SqlParameter("NTID", xNTID)).ToList();
}
Don't double up on sqlparameter some people get burned doing this to their variable
var Action = new SqlParameter("@Action", 1); // Don't do this, as it is set below already.
What do you mean exactly? Do you want to reuse the result of your query for an other query?
In that case, why don't you combine both queries, by making the second query search inside the results of the first one (SELECT xxx in (SELECT yyy...)
You can use:
import operator
import functools
functools.reduce(operator.mul, [1,2,3,4,5,6], 1)
See reduce
and operator.mul
documentations for an explanation.
You need the import functools
line in Python 3+.
You can specify both max post size and max file size limit in php.ini
post_max_size = 64M
upload_max_filesize = 64M
'JavaScript accessing Google Docs' would be tedious to implement and moreover Google documentation is also not that simple to get it. I have some good links to share by which you can achieve js access to gdoc:
http://code.google.com/apis/documents/docs/3.0/developers_guide_protocol.html#UploadingDocs
http://code.google.com/apis/spreadsheets/gadgets/
May be these would help you out..
Warn/confirm User if Back button is Pressed is as below.
window.onbeforeunload = function() { return "Your work will be lost."; };
You can get more information using below mentioned links.
Disable Back Button in Browser using JavaScript
I hope this will help to you.
I had the same problem. In my case it turned out I had installed another version of the sdk alongside the version provided by Android Studio. Changing my ANDROID_SDK_ROOT environment variable to the original value fixed it for me.
By default .vs folder is hidden (at least in my case).
If you are not able to find the .vs folder, follow the below steps.
Attributes
section, click Hidden
check box(default unchecked),step 3
, this time you need to uncheck
the 'Hidden' option that you checked previously.Now should be able to see .vs folder.
Inspired by the internal callback above, i made a function to fire a callback at fractions of minutes. If timeout is set to intervals like 6 000, 15 000, 30 000, 60 000 it will continuously adapt the intervals in sync to the exact transition to the next minute of your system clock.
//Interval timer to trigger on even minute intervals
function setIntervalSynced(callback, intervalMs) {
//Calculate time to next modulus timer event
var betterInterval = function () {
var d = new Date();
var millis = (d.getMinutes() * 60 + d.getSeconds()) * 1000 + d.getMilliseconds();
return intervalMs - millis % intervalMs;
};
//Internal callback
var internalCallback = function () {
return function () {
setTimeout(internalCallback, betterInterval());
callback();
}
}();
//Initial call to start internal callback
setTimeout(internalCallback, betterInterval());
};
Share Any File as below ( Kotlin ) :
first create a folder named xml
in the res
folder and create a new XML Resource File named provider_paths.xml
and put the below code inside it :
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path
name="files"
path="."/>
<external-path
name="external_files"
path="."/>
</paths>
now go to the manifests
folder and open the AndroidManifest.xml
and then put the below code inside the <application>
tag :
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" /> // provider_paths.xml file path in this example
</provider>
now you put the below code in the setOnLongClickListener
:
share_btn.setOnClickListener {
try {
val file = File("pathOfFile")
if(file.exists()) {
val uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file)
val intent = Intent(Intent.ACTION_SEND)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.setType("*/*")
intent.putExtra(Intent.EXTRA_STREAM, uri)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent)
}
} catch (e: java.lang.Exception) {
e.printStackTrace()
toast("Error")
}
}
As the accepted solution of @Shane is not supported in RStudio (see here) as of now (Sep 2015), I would like to add an advice to @James Thompson answer regarding workflow:
If you use SumatraPDF as viewer you do not need to close the PDF file before making changes to it. Sumatra does not put a opened file in read-only and thus does not prevent it from being overwritten. Therefore, once you opened your PDF file with Sumatra, changes out of RStudio (or any other R IDE) are immediately displayed in Sumatra.
For Kotlin !!
Custom Array adapter to hide the last item of the spinner
import android.content.Context
import android.widget.ArrayAdapter
import android.widget.Spinner
class HintAdapter<T>(context: Context, resource: Int, objects: Array<T>) :
ArrayAdapter<T>(context, resource, objects) {
override fun getCount(): Int {
val count = super.getCount()
// The last item will be the hint.
return if (count > 0) count - 1 else count
}
}
Spinner Extension function to set hint on spinner
fun Spinner.addHintWithArray(context: Context, stringArrayResId: Int) {
val hintAdapter =
HintAdapter<String>(
context,
android.R.layout.simple_spinner_dropdown_item,
context.resources.getStringArray(stringArrayResId)
)
hintAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
adapter = hintAdapter
setSelection(hintAdapter.count)
}
How to use: add the extension by passing context and array on Spinner
spinnerMonth.addHintWithArray(context, R.array.months)
Note: The hint should be the last item of your string array
<string-array name="months">
<item>Jan</item>
<item>Feb</item>
<item>Mar</item>
<item>Apr</item>
<item>May</item>
<item>Months</item>
</string-array>
Swift 2.1.1 below works:
func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let v = UIView()
v.backgroundColor = UIColor.RGB(53, 60, 62)
return v
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 80
}
If use self.theTable.tableFooterView = tableFooter
there is a space between last row and tableFooterView
.
Note that if you use Android Studio and download through its SDK Manager, the SDK is downloaded to ~/Library/Android/sdk
by default, not ~/.android-sdk-macosx
.
I would rather add this as a comment to @brismuth's excellent answer, but it seems I don't have enough reputation points yet.
The answer from @edutesoy points to the documentation of PowerMockito
and mentions constructor mocking as a hint but doesn't mention how to apply that to the current problem in the question.
Here is a solution based on that. Taking the code from the question:
public class MyClass {
void method1 {
MyObject obj1 = new MyObject();
obj1.method1();
}
}
The following test will create a mock of the MyObject
instance class via preparing the class that instantiates it (in this example I am calling it MyClass
) with PowerMock
and letting PowerMockito
to stub the constructor of MyObject
class, then letting you stub the MyObject
instance method1()
call:
@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)
public class MyClassTest {
@Test
public void testMethod1() {
MyObject myObjectMock = mock(MyObject.class);
when(myObjectMock.method1()).thenReturn(<whatever you want to return>);
PowerMockito.whenNew(MyObject.class).withNoArguments().thenReturn(myObjectMock);
MyClass objectTested = new MyClass();
objectTested.method1();
... // your assertions or verification here
}
}
With that your internal method1()
call will return what you want.
If you like the one-liners you can make the code shorter by creating the mock and the stub inline:
MyObject myObjectMock = when(mock(MyObject.class).method1()).thenReturn(<whatever you want>).getMock();
If you are taking a 'fill in the blank' approach, you can precisely position text anywhere you want on the page. So it's relatively easy (if not a bit tedious) to add the missing text to the document. For example with Zend Framework:
<?php
require_once 'Zend/Pdf.php';
$pdf = Zend_Pdf::load('blank.pdf');
$page = $pdf->pages[0];
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
$page->setFont($font, 12);
$page->drawText('Hello world!', 72, 720);
$pdf->save('zend.pdf');
If you're trying to replace inline content, such as a "[placeholder string]," it gets much more complicated. While it's technically possible to do, you're likely to mess up the layout of the page.
A PDF document is comprised of a set of primitive drawing operations: line here, image here, text chunk there, etc. It does not contain any information about the layout intent of those primitives.
EDIT: Starting from IPython 3 (now Jupyter project), the notebook has a text editor that can be used as a more convenient alternative to load/edit/save text files.
A text file can be loaded in a notebook cell with the magic command %load
.
If you execute a cell containing:
%load filename.py
the content of filename.py
will be loaded in the next cell. You can edit and execute it as usual.
To save the cell content back into a file add the cell-magic %%writefile filename.py
at the beginning of the cell and run it. Beware that if a file with the same name already exists it will be silently overwritten.
To see the help for any magic command add a ?
: like %load?
or %%writefile?
.
For general help on magic functions type "%magic" For a list of the available magic functions, use %lsmagic. For a description of any of them, type %magic_name?, e.g. '%cd?'.
See also: Magic functions from the official IPython docs.
A simpler way is
ggplot(data=df, aes(x=xvar, y=yvar)) +
geom_point()
ggsave(path = path, width = width, height = height, device='tiff', dpi=700)
As Luca indicated, add extra []
to your string and use the code below:
var myObject = eval('(' + myJSONtext + ')');
to test it you can use the snippet below.
var s =" [{'id':1,'name':'Test1'},{'id':2,'name':'Test2'}]";
var myObject = eval('(' + s + ')');
for (i in myObject)
{
alert(myObject[i]["name"]);
}
hope it helps..
Use your console:
console.log(object);
Or if you are inspecting html dom elements use console.dir(object). Example:
let element = document.getElementById('alertBoxContainer');
console.dir(element);
Or if you have an array of js objects you could use:
console.table(objectArr);
If you are outputting a lot of console.log(objects) you can also write
console.log({ objectName1 });
console.log({ objectName2 });
This will help you label the objects written to console.
Take a look at some of the crazy parsing examples in .Net's IPAddress.Parse: (MSDN)
"65536" ==> 0.0.255.255
"20.2" ==> 20.0.0.2
"20.65535" ==> 20.0.255.255
"128.1.2" ==> 128.1.0.2
Yes, you can do that.
There are some interesting use cases: Some browsers and plugins parse meta elements and change their behavior for different values.
<meta name="SKYPE_TOOLBAR" content="SKYPE_TOOLBAR_PARSER_COMPATIBLE">
<meta name="format-detection" content="telephone=no">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
This one can be changed by JavaScript. See: A fix for iPhone viewport scale bug
Some user agents (Opera for example) use the description for bookmarks. You can add personalized content here. Example:
<!DOCTYPE html>
<title>Test</title>
<meta name="description" content="this is old">
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.2.js'></script>
<button>Change description</button>
<script type='text/javascript'>
$('button').on('click', function() {
// Just replacing the value of the 'content' attribute will not work.
$('meta[name=description]').remove();
$('head').append( '<meta name="description" content="this is new">' );
});
</script>
So, it’s not just about search engines.
Your pip
is a soft link to the same executable file path with pip3
.
you can use the commands below to check where your pip
and pip3
real paths are:
$ ls -l `which pip`
$ ls -l `which pip3`
You may also use the commands below to know more details:
$ pip show pip
$ pip3 show pip
When we install different versions of python, we may create such soft links to
It is the same situation with python
, python2
, python3
More information below if you're interested in how it happens in different cases:
As has been said elsewhere, the answer is to git add
the file. e.g.:
git add path/to/untracked-file
git stash
However, the question is also raised in another answer: What if you don't really want to add the file? Well, as far as I can tell, you have to. And the following will NOT work:
git add -N path/to/untracked/file # note: -N is short for --intent-to-add
git stash
this will fail, as follows:
path/to/untracked-file: not added yet
fatal: git-write-tree: error building trees
Cannot save the current index state
So, what can you do? Well, you have to truly add the file, however, you can effectively un-add it later, with git rm --cached
:
git add path/to/untracked-file
git stash save "don't forget to un-add path/to/untracked-file" # stash w/reminder
# do some other work
git stash list
# shows:
# stash@{0}: On master: don't forget to un-add path/to/untracked-file
git stash pop # or apply instead of pop, to keep the stash available
git rm --cached path/to/untracked-file
And then you can continue working, in the same state as you were in before the git add
(namely with an untracked file called path/to/untracked-file
; plus any other changes you might have had to tracked files).
Another possibility for a workflow on this would be something like:
git ls-files -o > files-to-untrack
git add `cat files-to-untrack` # note: files-to-untrack will be listed, itself!
git stash
# do some work
git stash pop
git rm --cached `cat files-to-untrack`
rm files-to-untrack
[Note: As mentioned in a comment from @mancocapac, you may wish to add --exclude-standard
to the git ls-files
command (so, git ls-files -o --exclude-standard
).]
... which could also be easily scripted -- even aliases would do (presented in zsh syntax; adjust as needed) [also, I shortened the filename so it all fits on the screen without scrolling in this answer; feel free to substitute an alternate filename of your choosing]:
alias stashall='git ls-files -o > .gftu; git add `cat .gftu`; git stash'
alias unstashall='git stash pop; git rm --cached `cat .gftu`; rm .gftu'
Note that the latter might be better as a shell script or function, to allow parameters to be supplied to git stash
, in case you don't want pop
but apply
, and/or want to be able to specify a specific stash, rather than just taking the top one. Perhaps this (instead of the second alias, above) [whitespace stripped to fit without scrolling; re-add for increased legibility]:
function unstashall(){git stash "${@:-pop}";git rm --cached `cat .gftu`;rm .gftu}
Note: In this form, you need to supply an action argument as well as the identifier if you're going to supply a stash identifier, e.g. unstashall apply stash@{1}
or unstashall pop stash@{1}
Which of course you'd put in your .zshrc
or equivalent to make exist long-term.
Hopefully this answer is helpful to someone, putting everything together all in one answer.
You can use the following:
type
keyword, aliasing a function literal)Here is an example of how to use them:
type myCallbackType = (arg1: string, arg2: boolean) => number;
interface myCallbackInterface { (arg1: string, arg2: boolean): number };
class CallbackTest
{
// ...
public myCallback2: myCallbackType;
public myCallback3: myCallbackInterface;
public myCallback1: (arg1: string, arg2: boolean) => number;
// ...
}
In a nutshell, no.
However, there are "nice" things you can do.
INSERT dbo.SPCall (What, When) VALUES (OBJECT_NAME(@@PROCID), GETDATE()
"There are "fun" things you can do:
RAISERROR ('Warning: pwn3d: call admin', 16, 1)
, see who callsWAITFOR DELAY '00:01:00'
, see who callsYou get the idea. The tried-and-tested "see who calls" method of IT support.
If the reports are Reporting Services, then you can mine the RS database for the report runs if you can match code to report DataSet.
You couldn't rely on DMVs anyway because they are reset om SQL Server restart. Query cache/locks are transient and don't persist for any length of time.
For those who still struggle with this problem in Xcode8. For me was a duplicate Certificate problem, this is how I solved it:
I read the answer of Nick and then I began my investigation. I checked all the keys and Certificates in my particular case (inside ~/Library/Keychains/System.keychain).
When I opened the file, I found that I had two iPhone Distribution Certificates (that was the certificate that Xcode was requesting me), one with the iOS Distribution private key that I have been using since the beginning, and another iPhone Distribution Certificate which its private Key had a name (iOS Distribution:NAME) that wasn´t familiar for me. I deleted this last certificate, started Xcode again and the problem was gone. xCode wasn´t able to resolve that conflict and that´s why it was giving signing certificate error all the time.
Check your keychains, maybe you have a duplicate certificate.
The right way is to declare function prototype in header.
main.h
#ifndef MAIN_H
#define MAIN_H
int some_main(const char *name);
#endif
main.c
#include "main.h"
int main()
{
some_main("Hello, World\n");
}
int some_main(const char *name)
{
printf("%s", name);
}
Alternative with one file (main.c)
static int some_main(const char *name);
int some_main(const char *name)
{
// do something
}
position: absolute
will position the element by coordinates, relative to the closest positioned ancestor, i.e. the closest parent which isn't position: static
.
Have your four divs nested inside the target div, give the target div position: relative
, and use position: absolute
on the others.
Structure your HTML similar to this:
<div id="container">
<div class="top left"></div>
<div class="top right"></div>
<div class="bottom left"></div>
<div class="bottom right"></div>
</div>
And this CSS should work:
#container {
position: relative;
}
#container > * {
position: absolute;
}
.left {
left: 0;
}
.right {
right: 0;
}
.top {
top: 0;
}
.bottom {
bottom: 0;
}
...
savefig
has its own parameter for facecolor
.
I think an even easier way than the accepted answer is to set them globally just once, instead of putting facecolor=fig.get_facecolor()
every time:
plt.rcParams['axes.facecolor']='red'
plt.rcParams['savefig.facecolor']='red'
iOS 4.3.2's User Agent, which came out this week, is:
Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5
A less known difference is that in operating systems with optimistic memory allocation, like Linux, the pointer returned by malloc
isn't backed by real memory until the program actually touches it.
calloc
does indeed touch the memory (it writes zeroes on it) and thus you'll be sure the OS is backing the allocation with actual RAM (or swap). This is also why it is slower than malloc (not only does it have to zero it, the OS must also find a suitable memory area by possibly swapping out other processes)
See for instance this SO question for further discussion about the behavior of malloc
Doesn't have to be; "64-bit machine" can mean many things, but typically means that the CPU has registers that big. The sizeof a type is determined by the compiler, which doesn't have to have anything to do with the actual hardware (though it typically does); in fact, different compilers on the same machine can have different values for these.
I'm not sure if you want to find duplicate files or just compare two single files. If the latter, the above approach (filecmp) is better, if the former, the following approach is better.
There are lots of duplicate files detection questions here. Assuming they are not very small and that performance is important, you can
Here's is an answer with Python implementations (I prefer the one by nosklo, BTW)
Notepad++ provides 2 types of features:
Based on what you write, it seems what you want is auto-completion on function only + suggestion on arguments.
To do that, you just need to change a setting.
Settings
> Preferences...
> Auto-completion
Enable Auto-completion on each input
Function completion
and not Word completion
Function parameter hint on input
(if you have this option)On version 6.5.5 of Notepad++, I have this setting
Some documentation about auto-completion is available in Notepad++ Wiki.
I also prefer CSS over HTML; HTML is about content, CSS about presentation.
With CSS you have three options.
Example using internal stylesheet:
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Image with border</title>
<style type="text/css">
img.hasBorder { border:15px solid #66CC33; }
</style>
</head>
<body>
<img class="hasBorder" src="peggy.jpg" alt="" />
</body>
</html>
If you want an external stylesheet, replace the <style>...</style> block with
<link rel="stylesheet" type="text/css" href="somestylesheet.css" />
Add an EditText on top of your listview in its .xml layout file. And in your activity/fragment..
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
lv.setAdapter(adapter);
inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
@Override
public void afterTextChanged(Editable arg0) {}
});
The basic here is to add an OnTextChangeListener to your edit text and inside its callback method apply filter to your listview's adapter.
EDIT
To get filter to your custom BaseAdapter you"ll need to implement Filterable interface.
class CustomAdapter extends BaseAdapter implements Filterable {
public View getView(){
...
}
public Integer getCount()
{
...
}
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
arrayListNames = (List<String>) results.values;
notifyDataSetChanged();
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<String> FilteredArrayNames = new ArrayList<String>();
// perform your search here using the searchConstraint String.
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mDatabaseOfNames.size(); i++) {
String dataNames = mDatabaseOfNames.get(i);
if (dataNames.toLowerCase().startsWith(constraint.toString())) {
FilteredArrayNames.add(dataNames);
}
}
results.count = FilteredArrayNames.size();
results.values = FilteredArrayNames;
Log.e("VALUES", results.values.toString());
return results;
}
};
return filter;
}
}
Inside performFiltering() you need to do actual comparison of the search query to values in your database. It will pass its result to publishResults() method.
Does your search algorithm continually decrease the word list as your search continues?
For instance, in the search above there are only 13 letters that your words can start with (effectively reducing to half as many starting letters).
As you add more letter permutations it would further decrease the available word sets decreasing the searching necessary.
I'd start there.
Take a look at OAuth 2.0 playground.You will get an overview of the protocol.It is basically an environment(like any app) that shows you the steps involved in the protocol.
i had a situation where i can't change old code, so added this javascript function to calculate center point and zoom level:
//input_x000D_
var tempdata = ["18.9400|72.8200-19.1717|72.9560-28.6139|77.2090"];_x000D_
_x000D_
function getCenterPosition(tempdata){_x000D_
var tempLat = tempdata[0].split("-");_x000D_
var latitudearray = [];_x000D_
var longitudearray = [];_x000D_
var i;_x000D_
for(i=0; i<tempLat.length;i++){_x000D_
var coordinates = tempLat[i].split("|");_x000D_
latitudearray.push(coordinates[0]);_x000D_
longitudearray.push(coordinates[1]);_x000D_
}_x000D_
latitudearray.sort(function (a, b) { return a-b; });_x000D_
longitudearray.sort(function (a, b) { return a-b; });_x000D_
var latdifferenece = latitudearray[latitudearray.length-1] - latitudearray[0];_x000D_
var temp = (latdifferenece / 2).toFixed(4) ;_x000D_
var latitudeMid = parseFloat(latitudearray[0]) + parseFloat(temp);_x000D_
var longidifferenece = longitudearray[longitudearray.length-1] - longitudearray[0];_x000D_
temp = (longidifferenece / 2).toFixed(4) ;_x000D_
var longitudeMid = parseFloat(longitudearray[0]) + parseFloat(temp);_x000D_
var maxdifference = (latdifferenece > longidifferenece)? latdifferenece : longidifferenece;_x000D_
var zoomvalue; _x000D_
if(maxdifference >= 0 && maxdifference <= 0.0037) //zoom 17_x000D_
zoomvalue='17';_x000D_
else if(maxdifference > 0.0037 && maxdifference <= 0.0070) //zoom 16_x000D_
zoomvalue='16';_x000D_
else if(maxdifference > 0.0070 && maxdifference <= 0.0130) //zoom 15_x000D_
zoomvalue='15';_x000D_
else if(maxdifference > 0.0130 && maxdifference <= 0.0290) //zoom 14_x000D_
zoomvalue='14';_x000D_
else if(maxdifference > 0.0290 && maxdifference <= 0.0550) //zoom 13_x000D_
zoomvalue='13';_x000D_
else if(maxdifference > 0.0550 && maxdifference <= 0.1200) //zoom 12_x000D_
zoomvalue='12';_x000D_
else if(maxdifference > 0.1200 && maxdifference <= 0.4640) //zoom 10_x000D_
zoomvalue='10';_x000D_
else if(maxdifference > 0.4640 && maxdifference <= 1.8580) //zoom 8_x000D_
zoomvalue='8';_x000D_
else if(maxdifference > 1.8580 && maxdifference <= 3.5310) //zoom 7_x000D_
zoomvalue='7';_x000D_
else if(maxdifference > 3.5310 && maxdifference <= 7.3367) //zoom 6_x000D_
zoomvalue='6';_x000D_
else if(maxdifference > 7.3367 && maxdifference <= 14.222) //zoom 5_x000D_
zoomvalue='5';_x000D_
else if(maxdifference > 14.222 && maxdifference <= 28.000) //zoom 4_x000D_
zoomvalue='4';_x000D_
else if(maxdifference > 28.000 && maxdifference <= 58.000) //zoom 3_x000D_
zoomvalue='3';_x000D_
else_x000D_
zoomvalue='1';_x000D_
return latitudeMid+'|'+longitudeMid+'|'+zoomvalue;_x000D_
}
_x000D_
In addition to the most upvoted answer here, one can also chain axhline
after calling plot
on a pandas
's DataFrame
.
import pandas as pd
(pd.DataFrame([1, 2, 3])
.plot(kind='bar', color='orange')
.axhline(y=1.5));
As always in python, there are of course several ways to do it, but there is one obvious way to do it.
tmpdict["ONE"]["TWO"]["THREE"]
is the obvious way to do it.
When that does not fit well with your algorithm, that may be a hint that your structure is not the best for the problem.
If you just want to just save you repetative typing, you can of course alias a subset of the dict:
>>> two_dict = tmpdict['ONE']['TWO'] # now you can just write two_dict for tmpdict['ONE']['TWO']
>>> two_dict["spam"] = 23
>>> tmpdict
{'ONE': {'TWO': {'THREE': 10, 'spam': 23}}}
You don't. The server you are making the request to has to implement CORS to grant JavaScript from your website access. Your JavaScript can't grant itself permission to access another website.
To empty a particular collection in a database:
model.remove(function(err, p){
if(err){
throw err;
} else{
console.log('No Of Documents deleted:' + p);
}
});
Note:
That's basically a set of 2 simultaneous equations:
x*y = a
X+y = b
(using the mathematical convention of x and y for the variables to solve and a and b for arbitrary constants).
But the solution involves a quadratic equation (because of the x*y), so depending on the actual values of a and b, there may not be a solution, or there may be multiple solutions.
In android gradle 0.4.0 you can just do:
println System.env.HOME
classpath com.android.tools.build:gradle-experimental:0.4.0
I also had this question, but in my case I didn't want to use a regex, because my JSON value may contain quotation marks. Hopefully my answer will help others in the future.
I solved this issue by using a standard string slice to remove the first and last characters. This works for me, because I used JSON.stringify()
on the textarea
that produced it and as a result, I know that I'm always going to have the "
s at each end of the string.
In this generalized example, response
is the JSON object my AJAX returns, and key
is the name of my JSON key.
response.key.slice(1, response.key.length-1)
I used it like this with a regex replace
to preserve the line breaks and write the content of that key to a paragraph block in my HTML:
$('#description').html(studyData.description.slice(1, studyData.description.length-1).replace(/\\n/g, '<br/>'));
In this case, $('#description')
is the paragraph tag I'm writing to. studyData
is my JSON object, and description
is my key with a multi-line value.
Using Blob
as a source for an img
:
template:
<img [src]="url">
component:
public url : SafeResourceUrl;
constructor(private http: HttpClient, private sanitizer: DomSanitizer) {
this.getImage('/api/image.jpg').subscribe(x => this.url = x)
}
public getImage(url: string): Observable<SafeResourceUrl> {
return this.http
.get(url, { responseType: 'blob' })
.pipe(
map(x => {
const urlToBlob = window.URL.createObjectURL(x) // get a URL for the blob
return this.sanitizer.bypassSecurityTrustResourceUrl(urlToBlob); // tell Anuglar to trust this value
}),
);
}
Further reference about trusting save values
Try ng-inspector. Download the add-on for Firefox from the website http://ng-inspector.org/. It is not available on the Firefox add on menu.
http://ng-inspector.org/ - website
http://ng-inspector.org/ng-inspector.xpi - Firefox Add-on?
You don't need a generate bock if you want all the bits of temp
assigned in the same always block.
parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
always @(posedge sysclk) begin
for (integer c=0; c<ROWBITS; c=c+1) begin: test
temp[c] <= 1'b0;
end
end
Alternatively, if your simulator supports IEEE 1800 (SytemVerilog), then
parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
always @(posedge sysclk) begin
temp <= '0; // fill with 0
end
end
Just a tip.. Temporary tables in Oracle are different to SQL Server. You create it ONCE and only ONCE, not every session. The rows you insert into it are visible only to your session, and are automatically deleted (i.e., TRUNCATE
, not DROP
) when you end you session ( or end of the transaction, depending on which "ON COMMIT" clause you use).
$("#message").css({"width" : "550px", "height" : "300px", "font-size" : "8pt"});
Also, it may be better to use jQuery's built in addClass
to make your project more scalable.
Keyboard shortcuts for VSCode on MacOS: https://code.visualstudio.com/shortcuts/keyboard-shortcuts-macos.pdf
I use ?/ to toggle commenting.
Set the version number to "1.0.*" and it will automatically fill in the last two number with the date (in days from some point) and the time (half the seconds from midnight)
Using Angular latest version (1.2.1) and track by $index
. This issue is fixed
<div ng-repeat="(i, name) in names track by $index">
Value: {{name}}
<input ng-model="names[i]">
</div>
The (m)
indicates the column display width; applications such as the MySQL client make use of this when showing the query results.
For example:
| v | a | b | c |
+-----+-----+-----+-----+
| 1 | 1 | 1 | 1 |
| 10 | 10 | 10 | 10 |
| 100 | 100 | 100 | 100 |
Here a
, b
and c
are using TINYINT(1)
, TINYINT(2)
and TINYINT(3)
respectively. As you can see, it pads the values on the left side using the display width.
It's important to note that it does not affect the accepted range of values for that particular type, i.e. TINYINT(1)
still accepts [-128 .. 127]
.
You can use console.log()
in Firebug or Chrome to get a good object view here, like this:
$.getJSON('my.json', function(data) {
console.log(data);
});
If you just want to view the string, look at the Resource view in Chrome or the Net view in Firebug to see the actual string response from the server (no need to convert it...you received it this way).
If you want to take that string and break it down for easy viewing, there's an excellent tool here: http://json.parser.online.fr/
The above description wasn't sufficient to get things working for me (probably dense or lazy) so I created this script once I found the answer to help me in the future. Hope it helps others
vim fixperms.sh
#!/bin/sh
for D in `find . -type d`
do
echo $D;
chown -R mysql:mysql $D;
chmod -R 660 $D;
chown mysql:mysql $D;
chmod 700 $D;
done
echo Dont forget to restart mysql: /etc/init.d/mysqld restart;
works in rails 4.1 and support symbols without quotes {:a => 'b'}
just add this to initializers folder:
class String
def to_hash_object
JSON.parse(self.gsub(/:([a-zA-z]+)/,'"\\1"').gsub('=>', ': ')).symbolize_keys
end
end
If you are using kotlin,consider these library. It's build for kotlin language.
AndroidHttpServer is a simple demo using ServerSocket to handle http request
https://github.com/weeChanc/AndroidHttpServer
https://github.com/ktorio/ktor
AndroidHttpServer is very small , but the feature is less as well.
Ktor is a very nice library,and the usage is simple too
As mentioned above using unpack
function of struct is a good way. If you want to implement your own function there is an another solution:
def bytes_to_int(bytes):
result = 0
for b in bytes:
result = result * 256 + int(b)
return result
SELECT d1.Short_Code
FROM domain1 d1
LEFT JOIN domain2 d2
ON d1.Short_Code = d2.Short_Code
WHERE d2.Short_Code IS NULL
Everyone seems to want to tell you what you should be doing rather than just answering the question.
The problem is that you're running the module as '__main__' by passing the mod1.py as an argument to the interpreter.
From PEP 328:
Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.
In Python 2.6, they're adding the ability to reference modules relative to the main module. PEP 366 describes the change.
Update: According to Nick Coghlan, the recommended alternative is to run the module inside the package using the -m switch.
I had this issue on Linux (CentOS 7 64 bit) with 32-bit Eclipse Neon and 32-bit JRE 8. Non of the answers here or in similar questions were helpful, so I thought it can help someone.
Equinox launcher (eclipse
executable) is reading the plugins/
directory and then searches for eclipse_xxxx.so/dll
in org.eclipse.equinox.launcher.<os>_<version>/
. Typically, the problem is in eclipse.ini
pointing to the wrong version of Equinox launcher plugin. But, if the file system uses 64-bit inodes, such as XFS and one of the files gets inode
number above 4294967296, then the launcher fails reading the plugins/
directory and this error message pops up. Use ls -li <eclipse>/plugins/
to check the inode
numbers.
In my case, moving to another mount with 32-bit inodes
resolved the problem.
Its undefined
because, console.log(response)
runs before doCall(urlToCall);
is finished. You have to pass in a callback function aswell, that runs when your request is done.
First, your function. Pass it a callback:
function doCall(urlToCall, callback) {
urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
return callback(finalData);
});
}
Now:
var urlToCall = "http://myUrlToCall";
doCall(urlToCall, function(response){
// Here you have access to your variable
console.log(response);
})
@Rodrigo, posted a good resource in the comments. Read about callbacks in node and how they work. Remember, it is asynchronous code.
PFX files are PKCS#12 Personal Information Exchange Syntax Standard bundles. They can include arbitrary number of private keys with accompanying X.509 certificates and a certificate authority chain (set certificates).
If you want to extract client certificates, you can use OpenSSL's PKCS12 tool.
openssl pkcs12 -in input.pfx -out mycerts.crt -nokeys -clcerts
The command above will output certificate(s) in PEM format. The ".crt" file extension is handled by both macOS and Window.
You mention ".cer" extension in the question which is conventionally used for the DER encoded files. A binary encoding. Try the ".crt" file first and if it's not accepted, easy to convert from PEM to DER:
openssl x509 -inform pem -in mycerts.crt -outform der -out mycerts.cer
Another way of achieving it would be to temporary edit the gitignore file, add the file and then revert back the gitignore. A bit hacky i feel
You should use a datastore and proxy in ExtJs. There are plenty of examples of this, and the JSON reader automatically parses the JSON message into the model you specified.
There is no need to use basic Javascript when using ExtJs, everything is different, you should use the ExtJs ways to get everything right. Read there documentation carefully, it's good.
By the way, these examples also hold for Sencha Touch (especially v2), which is based on the same core functions as ExtJs.
Suspended. The session is waiting for an event, such as I/O, to complete.
Address already in use
means that the port
you are trying to allocate for your current execution is already occupied/allocated to some other process.
If you are a developer and if you are working on an application which require lots of testing, you might have an instance of your same application running in background (may be you forgot to stop it properly)
So if you encounter this error, just see which application/process is using the port.
In linux try using netstat -tulpn
. This command will list down a process list with all running processes.
Check if an application is using your port. If that application or process is another important one then you might want to use another port which is not used by any process/application.
Anyway you can stop the process which uses your port and let your application take it.
If you are in linux environment try,
netstat -tulpn
to display the processeskill <pid>
This will terminate the processIf you are using windows,
netstat -a -o -n
to check for the port usagestaskkill /F /PID <pid>
to kill that processAhem, because 22 is the port number for ssh and has been for ages?
Kindly check whether you have installed right version of ChromeDriver or not . In my case , installing correct version helped.
I know this is an old question, but I had the same problem and solved it thanks to this answer.
I use Putty regularly and have never had any problems. I use and have always used public key authentication. Today I could not connect again to my server, without changing any settings.
Then I saw the answer and remembered that I inadvertently ran chmod 777 .
in my user's home directory. I connected from somewhere else and simply ran chmod 755 ~
. Everything was back to normal instantly, I didn't even have to restart sshd.
I hope I saved some time from someone
We may need to check internet connectivity more than once. So it will be easier for us if we write the code block in an extension method of Context
. Below are my helper extensions for Context
and Fragment
.
Checking Internet Connection
fun Context.hasInternet(): Boolean {
val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return if (Build.VERSION.SDK_INT < 23) {
val activeNetworkInfo = connectivityManager.activeNetworkInfo
activeNetworkInfo != null && activeNetworkInfo.isConnected
} else {
val nc = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
if (nc == null) {
false
} else {
nc.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
}
}
}
Other Extensions
fun Context.hasInternet(notifyNoInternet: Boolean = true, trueFunc: (internet: Boolean) -> Unit) {
if (hasInternet()) {
trueFunc(true)
} else if (notifyNoInternet) {
Toast.makeText(this, "No Internet Connection!", Toast.LENGTH_SHORT).show()
}
}
fun Context.hasInternet(
trueFunc: (internet: Boolean) -> Unit,
falseFunc: (internet: Boolean) -> Unit
) {
if (hasInternet()) {
trueFunc(true)
} else {
falseFunc(true)
}
}
fun Fragment.hasInternet(): Boolean = context!!.hasInternet()
fun Fragment.hasInternet(notifyNoInternet: Boolean = true, trueFunc: (internet: Boolean) -> Unit) =
context!!.hasInternet(notifyNoInternet, trueFunc)
fun Fragment.hasInternet(
trueFunc: (internet: Boolean) -> Unit, falseFunc: (internet: Boolean) -> Unit
) = context!!.hasInternet(trueFunc, falseFunc)
A slight modification of this to change the \voffset
works for me:
\newenvironment{changemargin}[1]{
\begin{list}{}{
\setlength{\voffset}{#1}
}
\item[]}{\end{list}}
And then put your figures in a \begin{changemargin}{-1cm}...\end{changemargin}
environment.
@delato468 comment must be listed as a solution as it worked for me.
In addition to defining the parameter, the user must pass it too at the time of calling the function
fetch_data(PDO $pdo, $cat_id)
I have Android Studio 2.1.1 Bro use genymotion emulator It Faster If Use Android Marshmallow. And My Ram Is 4gb.And Install Plugin for genymotion in Android Studio.You Will see good result in instead of wasting time start android emualtor it will take 5 min.genymotion 10 to 20 second speed and faster so I recommended to you use genymotion.
I had this problem where my SQL server rounds up 0.5 to 1 while my C# application didn't. So you would see two different results.
Here's an implementation with int/long. This is how Java rounds.
int roundedNumber = (int)Math.Floor(d + 0.5);
It's probably the most efficient method you could think of as well.
If you want to keep it a double and use decimal precision , then it's really just a matter of using exponents of 10 based on how many decimal places.
public double getRounding(double number, int decimalPoints)
{
double decimalPowerOfTen = Math.Pow(10, decimalPoints);
return Math.Floor(number * decimalPowerOfTen + 0.5)/ decimalPowerOfTen;
}
You can input a negative decimal for decimal points and it's word fine as well.
getRounding(239, -2) = 200
Assuming you can put ID's on the inputs:
$('#name').change(function() {
$('#firstname').val($(this).val());
});
Otherwise you'll have to select using the names:
$('input[name="name"]').change(function() {
$('input[name="firstname"]').val($(this).val());
});
If earlier working project crashing suddenly with mentioned error you can try following solution.
This worked for me.
You are assigning an onclick
event inside an function.
That means once the function has executed once, the second onclick
event is assigned to the element as well.
Either assign the function
onclick
or use jqueryclick()
.
There's no need to have both
Go to %appdata%\Notepad++ folder.
The macro definitions are held in shortcuts.xml inside the <Macros>
tag. You can copy the whole file, or copy the tag and paste it into shortcuts.xml at the other location.
In the latter case, be sure to use another editor, since N++ overwrites shortcuts.xml on exit.
In order for z-index to work, you'll need to give the element a position:absolute
or a position:relative
property. Once you do that, your links will function properly, though you may have to tweak your CSS a bit afterwards.
/System/Library/Frameworks/JavaVM.framework/
Also see Java 7 path on mountain lion
All you need to do is configure your SSH setup with multiple SSH keypairs.
This link is easy to follow (Thanks Eric): http://code.tutsplus.com/tutorials/quick-tip-how-to-work-with-github-and-multiple-accounts--net-22574
Generating SSH keys (Win/msysgit) https://help.github.com/articles/generating-an-ssh-key/
Also, if you're working with multiple repositories using different personas, you need to make sure that your individual repositories have the user settings overridden accordingly:
Setting user name, email and GitHub token – Overriding settings for individual repos https://help.github.com/articles/setting-your-commit-email-address-in-git/
Hope this helps.
Note:
Some of you may require different emails to be used for different repositories, from git 2.13 you can set the email on a directory basis by editing the global config file found at: ~/.gitconfig
using conditionals like so:
[user]
name = Pavan Kataria
email = [email protected]
[includeIf "gitdir:~/work/"]
path = ~/work/.gitconfig
And then your work specific config ~/work/.gitconfig would look like this:
[user]
email = [email protected]
Thank you @alexg for informing me of this in the comments.
var currentDate = new Date();
var firstday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay())).toUTCString();
var lastday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay() + 7)).toUTCString();
console.log(firstday, lastday)
_x000D_
if i remove .toUTCString(). output which i receive is not as expected
i had to use it for a condition add if you don't need the index
using System.Linq;
use
if(list.Any(x => x.Title == title){
// do something here
}
this will tell you if any variable satisfies your given condition.
There are two steps to fix this.
First edit phpMyAdmin/libraries/DatabaseInterface.class.php
Change:
if (PMA_MYSQL_INT_VERSION > 50503) {
$default_charset = 'utf8mb4';
$default_collation = 'utf8mb4_general_ci';
} else {
$default_charset = 'utf8';
$default_collation = 'utf8_general_ci';
}
To:
//if (PMA_MYSQL_INT_VERSION > 50503) {
// $default_charset = 'utf8mb4';
// $default_collation = 'utf8mb4_general_ci';
//} else {
$default_charset = 'utf8';
$default_collation = 'utf8_general_ci';
//}
Then delete this cookie from your browser "pma_collation_connection".
Or delete all Cookies.
Then restart your phpMyAdmin.
(It would be nice if phpMyAdmin allowed you to set the charset and collation per server in the config.inc.php)
If you want to use them as in swift 2, you can use these funcs:
For CGRectMake:
func CGRectMake(_ x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) -> CGRect {
return CGRect(x: x, y: y, width: width, height: height)
}
For CGPointMake:
func CGPointMake(_ x: CGFloat, _ y: CGFloat) -> CGPoint {
return CGPoint(x: x, y: y)
}
For CGSizeMake:
func CGSizeMake(_ width: CGFloat, _ height: CGFloat) -> CGSize {
return CGSize(width: width, height: height)
}
Just put them outside any class and it should work. (Works for me at least)
you seem to have not created an main method, which should probably look something like this (i am not sure)
class RunThis
{
public static void main(String[] args)
{
Calculate answer = new Calculate();
answer.getNumber1();
answer.getNumber2();
answer.setNumber(answer.getNumber1() , answer.getNumber2());
answer.getOper();
answer.setOper(answer.getOper());
answer.getAnswer();
}
}
the point is you should have created a main method under some class and after compiling you should run the .class file containing main method. In this case the main method is under RunThis i.e RunThis.class.
I am new to java this may or may not be the right answer, correct me if i am wrong
I decide to add on, rather than posting my solution to another post. Below are the solution that I build, may not be perfect, but so far the output are good.
Important: it will pass through all the points!
If you have any idea, to make it better, please share to me. Thanks.
Here are the comparison of before after:
Save this code to HTML to test it out.
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
<canvas id="myCanvas" width="1200" height="700" style="border:1px solid #d3d3d3;">Your browser does not support the HTML5 canvas tag.</canvas>_x000D_
<script>_x000D_
var cv = document.getElementById("myCanvas");_x000D_
var ctx = cv.getContext("2d");_x000D_
_x000D_
function gradient(a, b) {_x000D_
return (b.y-a.y)/(b.x-a.x);_x000D_
}_x000D_
_x000D_
function bzCurve(points, f, t) {_x000D_
//f = 0, will be straight line_x000D_
//t suppose to be 1, but changing the value can control the smoothness too_x000D_
if (typeof(f) == 'undefined') f = 0.3;_x000D_
if (typeof(t) == 'undefined') t = 0.6;_x000D_
_x000D_
ctx.beginPath();_x000D_
ctx.moveTo(points[0].x, points[0].y);_x000D_
_x000D_
var m = 0;_x000D_
var dx1 = 0;_x000D_
var dy1 = 0;_x000D_
_x000D_
var preP = points[0];_x000D_
for (var i = 1; i < points.length; i++) {_x000D_
var curP = points[i];_x000D_
nexP = points[i + 1];_x000D_
if (nexP) {_x000D_
m = gradient(preP, nexP);_x000D_
dx2 = (nexP.x - curP.x) * -f;_x000D_
dy2 = dx2 * m * t;_x000D_
} else {_x000D_
dx2 = 0;_x000D_
dy2 = 0;_x000D_
}_x000D_
ctx.bezierCurveTo(preP.x - dx1, preP.y - dy1, curP.x + dx2, curP.y + dy2, curP.x, curP.y);_x000D_
dx1 = dx2;_x000D_
dy1 = dy2;_x000D_
preP = curP;_x000D_
}_x000D_
ctx.stroke();_x000D_
}_x000D_
_x000D_
// Generate random data_x000D_
var lines = [];_x000D_
var X = 10;_x000D_
var t = 40; //to control width of X_x000D_
for (var i = 0; i < 100; i++ ) {_x000D_
Y = Math.floor((Math.random() * 300) + 50);_x000D_
p = { x: X, y: Y };_x000D_
lines.push(p);_x000D_
X = X + t;_x000D_
}_x000D_
_x000D_
//draw straight line_x000D_
ctx.beginPath();_x000D_
ctx.setLineDash([5]);_x000D_
ctx.lineWidth = 1;_x000D_
bzCurve(lines, 0, 1);_x000D_
_x000D_
//draw smooth line_x000D_
ctx.setLineDash([0]);_x000D_
ctx.lineWidth = 2;_x000D_
ctx.strokeStyle = "blue";_x000D_
bzCurve(lines, 0.3, 1);_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
An input
element does not support the target
attribute. The target
attribute is for a
tags and that is where it should be used.
You can use the following. They all wrap the window
object into a jQuery object.
$(window).load(function () {
topInViewport($("#mydivname"))
});
$(window).resize(function () {
topInViewport($("#mydivname"))
});
$(window).scroll(function () {
topInViewport($("#mydivname"))
});
Or bind to them all using on
:
$(window).on("load resize scroll",function(e){
topInViewport($("#mydivname"))
});
When none of the if
test in number_translator()
evaluate to true, the function returns None
. The error message is the consequence of that.
Whenever you see an error that include 'NoneType'
that means that you have an operand or an object that is None
when you were expecting something else.
We can add ng-click event conditionally without using disabled class.
HTML:
<div ng-repeat="object in objects">
<span ng-click="!object.status && disableIt(object)">{{object.value}}</span>
</div>
If you're feeling fancy:
$('.list-sort').attr('colspan', function(index, attr){
return attr == 6 ? null : 6;
});
Because, at least in HTML 4.01 and XHTML 1(.1), the type
attribute for <script>
elements is required.
In HTML 5, type
is no longer required.
In fact, while you should use text/javascript
in your HTML source, many servers will send the file with Content-type: application/javascript
. Read more about these MIME types in RFC 4329.
Notice the difference between RFC 4329, that marked text/javascript
as obsolete and recommending the use of application/javascript
, and the reality in which some browsers freak out on <script>
elements containing type="application/javascript"
(in HTML source, not the HTTP Content-type header of the file that gets send). Recently, there was a discussion on the WHATWG mailing list about this discrepancy (HTML 5's type
defaults to text/javascript
), read these messages with subject Will you consider about RFC 4329?
This is not a spring boot tutorial. It's the updated answer to a question on how to run a Maven build within a Docker container.
Question originally posted 4 years ago.
Use the spring initializer to generate a demo app
Extract the zip archive locally
#
# Build stage
#
FROM maven:3.6.0-jdk-11-slim AS build
COPY src /home/app/src
COPY pom.xml /home/app
RUN mvn -f /home/app/pom.xml clean package
#
# Package stage
#
FROM openjdk:11-jre-slim
COPY --from=build /home/app/target/demo-0.0.1-SNAPSHOT.jar /usr/local/lib/demo.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","/usr/local/lib/demo.jar"]
Note
docker build -t demo .
$ docker run --rm -it demo:latest
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.3.RELEASE)
2019-02-22 17:18:57.835 INFO 1 --- [ main] com.example.demo.DemoApplication : Starting DemoApplication v0.0.1-SNAPSHOT on f4e67677c9a9 with PID 1 (/usr/local/bin/demo.jar started by root in /)
2019-02-22 17:18:57.837 INFO 1 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: default
2019-02-22 17:18:58.294 INFO 1 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 0.711 seconds (JVM running for 1.035)
Read the Docker hub documentation on how the Maven build can be optimized to use a local repository to cache jars.
This question is now 4 years old and in that time it's fair to say building application using Docker has undergone significant change.
This new style enables you to create more light-weight images that don't encapsulate your build tools and source code.
The example here again uses the official maven base image to run first stage of the build using a desired version of Maven. The second part of the file defines how the built jar is assembled into the final output image.
FROM maven:3.5-jdk-8 AS build
COPY src /usr/src/app/src
COPY pom.xml /usr/src/app
RUN mvn -f /usr/src/app/pom.xml clean package
FROM gcr.io/distroless/java
COPY --from=build /usr/src/app/target/helloworld-1.0.0-SNAPSHOT.jar /usr/app/helloworld-1.0.0-SNAPSHOT.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","/usr/app/helloworld-1.0.0-SNAPSHOT.jar"]
Note:
I haven't used this approach but seems worthy of investigation as it enables you to build images without having to create nasty things like Dockerfiles :-)
https://github.com/GoogleContainerTools/jib
The project has a Maven plugin which integrates the packaging of your code directly into your Maven workflow.
Try using the new official images, there's one for Maven
https://registry.hub.docker.com/_/maven/
The image can be used to run Maven at build time to create a compiled application or, as in the following examples, to run a Maven build within a container.
The following command runs your Maven build inside a container:
docker run -it --rm \
-v "$(pwd)":/opt/maven \
-w /opt/maven \
maven:3.2-jdk-7 \
mvn clean install
Notes:
Run the Nexus container
docker run -d -p 8081:8081 --name nexus sonatype/nexus
Create a "settings.xml" file:
<settings>
<mirrors>
<mirror>
<id>nexus</id>
<mirrorOf>*</mirrorOf>
<url>http://nexus:8081/content/groups/public/</url>
</mirror>
</mirrors>
</settings>
Now run Maven linking to the nexus container, so that dependencies will be cached
docker run -it --rm \
-v "$(pwd)":/opt/maven \
-w /opt/maven \
--link nexus:nexus \
maven:3.2-jdk-7 \
mvn -s settings.xml clean install
Notes:
Take a look at the System.Net.WebClient
class, it can be used to issue requests and handle their responses, as well as to download files:
http://www.hanselman.com/blog/HTTPPOSTsAndHTTPGETsWithWebClientAndCAndFakingAPostBack.aspx
http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.90).aspx
After this:
INSERT INTO aspnet_GameProfiles(UserId, GameId) OUTPUT INSERTED.ID VALUES(@UserId, @GameId)
Execute this
int id = (int)command.ExecuteScalar;
It will work
Step 1: Firstly, Go to the Settings in your real device whose device are used to run android app.
Step 2: After that go to the “About phone” if Developer Options is not shown in your device
Step 3: Then Tap 7 times on Build number to create Developer Options.
Step 4: After that go back and Developer options will be created in your device.
Step 5: After that go to Developer options and Enable USB debugging in your device as shown in figure below.
Step 6: Connect your device with your system via data cable and after that allow USB debugging message shown on your device and press OK.
Step 7: After that Go to the menu bar and Run app as shown in figure below.
Step 8: If real device is connected to your system then it will show Online. Now click on your Mobile phone device and you App will be run in real device.
Step 9: After that your Android app run in Real device.
Regards, Guruji Softwares (https://gurujisoftwares.com)
Try this code:
@RequestMapping(value = "/validate", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<ErrorBean> validateUser(@QueryParam("jsonInput") final String jsonInput) {
int numberHTTPDesired = 400;
ErrorBean responseBean = new ErrorBean();
responseBean.setError("ERROR");
responseBean.setMensaje("Error in validation!");
return new ResponseEntity<ErrorBean>(responseBean, HttpStatus.valueOf(numberHTTPDesired));
}
Surprisingly for me, a bare-bones find is very much comparable to ls -f
> time ls -f my_dir | wc -l
17626
real 0m0.015s
user 0m0.011s
sys 0m0.009s
versus
> time find my_dir -maxdepth 1 | wc -l
17625
real 0m0.014s
user 0m0.008s
sys 0m0.010s
Of course, the values on the third decimal place shift around a bit every time you execute any of these, so they're basically identical. Notice however that find
returns one extra unit, because it counts the actual directory itself (and, as mentioned before, ls -f
returns two extra units, since it also counts . and ..).
All I needed was this :
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat sdfLocal = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
try {
String d = sdf.format(new Date());
System.out.println(d);
System.out.println(sdfLocal.parse(d));
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
Output : slightly dubious, but I want only the date to be consistent
2013.08.08 11:01:08
Thu Aug 08 11:01:08 GMT+08:00 2013
Now, 2017, you can do it easier with the new MSTest V2 Framework:
Assert.ThrowsException<Exception>(() => myClass.MyMethodWithError());
//async version
await Assert.ThrowsExceptionAsync<SomeException>(
() => myObject.SomeMethodAsync()
);
Most answers will tell you that you have a duplicate certificate. This is true for my case but the answers left out how to do it.
For me, my account expired and I have to get a new certificate and install it. Next, I looked at Keychain and removes the expired certificate but still got the error. What works for me is actually searching for "iPhone" in Keychain and removing all expired certificates. Apparently, some of it are not shown in System/Certificates or login/Certificates.
Hope this helps!
The iPhone6/6s/6+ are NOT designed to read passive NFC tags (aka Discovery Mode). There's a lot of misinformation on this topic, so I thought to provide some tangible info for developers to consider. The lack of NFC tag read support is not because of software but because of hardware. To understand why, you need to understand how NFC works. NFC works by way of Load Modulation. That means that the interrogator (PCD) emits a carrier magnetic field that energizes the passive target (PICC). With the potential generated by this carrier field, the target then is able to demodulate data coming from the interrogator and respond by modulating data over top of this very same field. The key here is that the target never creates a field of its own.
If you look at the iPhone6 teardown and parts list you will see the presence of a very small NFC loop antenna as well as the use of the AS3923 booster IC. This design was intended for custom microSD or SIM cards to enable mobile phones of old to do payments. This is the type of application where the mobile phone presents a Card Emulated credential to a high power contactless POS terminal. The POS terminal acts as the reader, energizing the iPhone6 with help from the AS3923 chip. The AS3923 block diagram clearly shows how the RX and TX modulation is boosted from a signal presented by a reader device. In other words the iPhone6 is not meant to provide a field, only to react to one. That's why it's design is only meant for NFC Card Emulation and perhaps Peer-2-Peer, but definitely not tag Discovery.
There are some alternatives to achieving tag Discovery with an iPhone6 using HW accessories. I talk about these integrations and how developers can architect solutions in this blog post. Our low power reader designs open interesting opportunities for mobile engagement that few developers are thinking about.
Disclosure: I'm the founder of Flomio, Inc., a TechStars company that delivers proximity ID hardware, software, and services for applications ranging from access control to payments.
Update: This rumor, if true, would open up the possibility for the iPhone to practically support NFC tag Discovery mode. An all glass design would not interfere with the NFC antenna as does the metal back of the current iPhone. We've attempted this design approach --albeit with cheaper materials-- on some of our custom reader designs with success so looking forward to this improvement.
Update: iOS11 has announced support for "NFC reader mode" for iPhone7/7+. Details here. API only supports reading NDEF messages (no ISO7816 APDUs) while an app is in the foreground (no background detection). Due out in the Fall, 2017... check the screenshot from WWDC keynote:
Following command connect to the remote server to dump a database:
<> optional params use them if you need them
output to a created folder with a name
mongodump --host --port --username --db --ssl --password --out _date+"%Y-%m-%d"
I think the best way to solve this problem is:
l = [1, 2, 3, 0, 0, 1]
while 0 in l:
l.remove(0)
Instead of iterating over list I remove 0
until there aren't any 0
in list
The problem is in this line:
with pattern.findall(row) as f:
You are using the with
statement. It requires an object with __enter__
and __exit__
methods. But pattern.findall
returns a list
, with
tries to store the __exit__
method, but it can't find it, and raises an error. Just use
f = pattern.findall(row)
instead.
I've made a proof-of-concept solution using jQuery.
I've now got this code in a Mercurial bitbucket repository. The main file is tables.html
.
I'm aware of one issue with this: if the table contains anchors, and if you open the URL with the specified anchor in a browser, when the page loads, the row with the anchor will probably be obscured by the floating header.
Update 2017-12-11: I see this doesn't work with current Firefox (57) and Chrome (63). Not sure when and why this stopped working, or how to fix it. But now, I think the accepted answer by Hendy Irawan is superior.
Yes, it's possible to use inline if-expressions:
{{ 'Update' if files else 'Continue' }}
SELECT
obj.name AS FK_NAME,
sch.name AS [schema_name],
tab1.name AS [table],
col1.name AS [column],
tab2.name AS [referenced_table],
col2.name AS [referenced_column]
FROM
sys.foreign_key_columns fkc
INNER JOIN sys.objects obj
ON obj.object_id = fkc.constraint_object_id
INNER JOIN sys.tables tab1
ON tab1.object_id = fkc.parent_object_id
INNER JOIN sys.schemas sch
ON tab1.schema_id = sch.schema_id
INNER JOIN sys.columns col1
ON col1.column_id = parent_column_id AND col1.object_id = tab1.object_id
INNER JOIN sys.tables tab2
ON tab2.object_id = fkc.referenced_object_id
INNER JOIN sys.columns col2
ON col2.column_id = referenced_column_id
AND col2.object_id = tab2.object_id;
In response to Haim Evgi's code, I added !== false to the end for it to work for me
$iPod = stripos($_SERVER['HTTP_USER_AGENT'],"iPod") !== false;
$iPhone = stripos($_SERVER['HTTP_USER_AGENT'],"iPhone") !== false;
$iPad = stripos($_SERVER['HTTP_USER_AGENT'],"iPad") !== false;
$Android = stripos($_SERVER['HTTP_USER_AGENT'],"Android") !== false;
pydoc is fantastic for generating documentation, but the documentation has to be written in the first place. You must have docstrings in your source code as was mentioned by RocketDonkey in the comments:
"""
This example module shows various types of documentation available for use
with pydoc. To generate HTML documentation for this module issue the
command:
pydoc -w foo
"""
class Foo(object):
"""
Foo encapsulates a name and an age.
"""
def __init__(self, name, age):
"""
Construct a new 'Foo' object.
:param name: The name of foo
:param age: The ageof foo
:return: returns nothing
"""
self.name = name
self.age = age
def bar(baz):
"""
Prints baz to the display.
"""
print baz
if __name__ == '__main__':
f = Foo('John Doe', 42)
bar("hello world")
The first docstring provides instructions for creating the documentation with pydoc. There are examples of different types of docstrings so you can see how they look when generated with pydoc.
When using @RestController
like this:
@RestController
public class HomeController {
@RequestMapping("/")
public String welcome() {
return "login";
}
}
This is the same as you do like this in a normal controller:
@Controller
public class HomeController {
@RequestMapping("/")
@ResponseBody
public String welcome() {
return "login";
}
}
Using @ResponseBody
returns return "login";
as a String object. Any object you return will be attached as payload
in the HTTP body as JSON.
This is why you are getting just login
in the response.
For Mac Users: The debug.keystore
file exists in ~/.android
directory. Sometimes, due to the relative path, the above mentioned error keeps on popping up.
You need to use the new
operator when creating the object
Contacts.add(new Data(name, address, contact)); // Creating a new object and adding it to list - single step
or else
Data objt = new Data(name, address, contact); // Creating a new object
Contacts.add(objt); // Adding it to the list
and your constructor shouldn't contain void
. Else it becomes a method in your class.
public Data(String n, String a, String c) { // Constructor has the same name as the class and no return type as such
This can be a good option if you want python completion as well as other languages. https://github.com/Valloric/YouCompleteMe
The python completion is jedi based same as jedi-vim.
Start with the use of tabs - the \t character modifier. It will advance to a fixed location (columns, terminal lingo).
However, it doesn't help if there are differences of more than the column width (4 characters, if I recall correctly).
To fix that, write your "OK/NOK" stuff using a fixed number of tabs (5? 6?, try it). Then return (\r) without new-lining, and write your message.
I prefer to use git rebase -i
for this job, because a nice list pops up where I can choose the commits to get rid of. It might not be as direct as some other answers here, but it just feels right.
Choose how many commits you want to list, then invoke like this (to enlist last three)
git rebase -i HEAD~3
Sample list
pick aa28ba7 Sanity check for RtmpSrv port
pick c26c541 RtmpSrv version option
pick 58d6909 Better URL decoding support
Then Git will remove commits for any line that you remove.
You are getting this error because you are not giving full path. (C:\Users...\file.exe) If you want to remove this error then either give full path or copy that application (you want to open) to the folder where your project(.exe) is present/saved.
#include <windows.h>
using namespace std;
int main()
{
system ("start C:\\Users\\Folder\\chrome.exe https://www.stackoverflow.com"); //for opening stackoverflow through google chrome , if chorme.exe is in that folder..
return 0;
}
Try jamspell - it works pretty well for automatic spelling correction:
import jamspell
corrector = jamspell.TSpellCorrector()
corrector.LoadLangModel('en.bin')
corrector.FixFragment('Some sentnec with error')
# u'Some sentence with error'
corrector.GetCandidates(['Some', 'sentnec', 'with', 'error'], 1)
# ('sentence', 'senate', 'scented', 'sentinel')
If you change from using a lambda with one argument to a function with one argument, you will get this error.
For example:
You had:
foobar = lambda do |baz|
puts baz
end
and you changed the definition to
def foobar(baz)
puts baz
end
And you left your invocation as:
foobar.call(baz)
And then you got the message
ArgumentError: wrong number of arguments (0 for 1)
when you really meant:
foobar(baz)
Use the annotation @Deprecated
for your method, and you should also mention it in your javadocs.
Just a simplification of the Tim's answer. The groovy way to do it is using a map, as already suggested, but then let's put the mandatory parameters also in the map. This will look like this:
def someMethod(def args) {
println "MANDATORY1=${args.mandatory1}"
println "MANDATORY2=${args.mandatory2}"
println "OPTIONAL1=${args?.optional1}"
println "OPTIONAL2=${args?.optional2}"
}
someMethod mandatory1:1, mandatory2:2, optional1:3
with the output:
MANDATORY1=1
MANDATORY2=2
OPTIONAL1=3
OPTIONAL2=null
This looks nicer and the advantage of this is that you can change the order of the parameters as you like.
As Xavier said, you can put your prebuilts in /src/main/jniLibs/ if you are using gradle 0.7.2+
taken from: https://groups.google.com/d/msg/adt-dev/nQobKd2Gl_8/ctDp9viWaxoJ
A good option is to avoid conversion from int
to enum
: for example, if you need the maximal value, you may compare x.ordinal() to y.ordinal() and return x or y correspondingly. (You may need to re-order you values to make such comparison meaningful.)
If that is not possible, I would store MyEnum.values()
into a static array.
Now click on Add a generic credential and provide the following values
(1) Internet or network adress: git:https://tfs.donamain name (2) username: your username (3) password: your password
this should fix it
You need to call the AddAddress
method once for every recipient. Like so:
$mail->AddAddress('[email protected]', 'Person One');
$mail->AddAddress('[email protected]', 'Person Two');
// ..
Better yet, add them as Carbon Copy recipients.
$mail->AddCC('[email protected]', 'Person One');
$mail->AddCC('[email protected]', 'Person Two');
// ..
To make things easy, you should loop through an array to do this.
$recipients = array(
'[email protected]' => 'Person One',
'[email protected]' => 'Person Two',
// ..
);
foreach($recipients as $email => $name)
{
$mail->AddCC($email, $name);
}
const romanize = num => {_x000D_
const romans = {_x000D_
M:1000,_x000D_
CM:900,_x000D_
D:500,_x000D_
CD:400,_x000D_
C:100,_x000D_
XC:90,_x000D_
L:50,_x000D_
XL:40,_x000D_
X:10,_x000D_
IX:9,_x000D_
V:5,_x000D_
IV:4,_x000D_
I:1_x000D_
};_x000D_
_x000D_
let roman = '';_x000D_
_x000D_
for (let key in romans) {_x000D_
const times = Math.trunc(num / romans[key]);_x000D_
roman += key.repeat(times);_x000D_
num -= romans[key] * times;_x000D_
}_x000D_
_x000D_
return roman;_x000D_
}_x000D_
_x000D_
console.log(_x000D_
romanize(38)_x000D_
)
_x000D_
Just styling an input type="submit"
like this worked for me:
.link-button { _x000D_
background: none;_x000D_
border: none;_x000D_
color: #0066ff;_x000D_
text-decoration: underline;_x000D_
cursor: pointer; _x000D_
}
_x000D_
<input type="submit" class="link-button" />
_x000D_
Tested in Chrome, IE 7-9, Firefox
This answer may not be the most efficient, but it sure is dynamic. Pairing native JDBC with Google's Gson library, I easily can convert from an SQL result to a JSON stream.
I have included the converter, example DB properties file, SQL table generation, and a Gradle build file (with dependencies used).
import java.io.PrintWriter;
import com.oracle.jdbc.ResultSetConverter;
public class QueryApp {
public static void main(String[] args) {
PrintWriter writer = new PrintWriter(System.out);
String dbProps = "/database.properties";
String indent = " ";
writer.println("Basic SELECT:");
ResultSetConverter.queryToJson(writer, dbProps, "SELECT * FROM Beatles", indent, false);
writer.println("\n\nIntermediate SELECT:");
ResultSetConverter.queryToJson(writer, dbProps, "SELECT first_name, last_name, getAge(date_of_birth) as age FROM Beatles", indent, true);
}
}
package com.oracle.jdbc;
import java.io.*;
import java.lang.reflect.Type;
import java.sql.*;
import java.util.*;
import com.google.common.reflect.TypeToken;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonWriter;
public class ResultSetConverter {
public static final Type RESULT_TYPE = new TypeToken<List<Map<String, Object>>>() {
private static final long serialVersionUID = -3467016635635320150L;
}.getType();
public static void queryToJson(Writer writer, String connectionProperties, String query, String indent, boolean closeWriter) {
Connection conn = null;
Statement stmt = null;
GsonBuilder gson = new GsonBuilder();
JsonWriter jsonWriter = new JsonWriter(writer);
if (indent != null) jsonWriter.setIndent(indent);
try {
Properties props = readConnectionInfo(connectionProperties);
Class.forName(props.getProperty("driver"));
conn = openConnection(props);
stmt = conn.createStatement();
gson.create().toJson(QueryHelper.select(stmt, query), RESULT_TYPE, jsonWriter);
if (closeWriter) jsonWriter.close();
stmt.close();
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
try {
if (stmt != null) stmt.close();
} catch (SQLException se2) {
}
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
try {
if (closeWriter && jsonWriter != null) jsonWriter.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
private static Properties readConnectionInfo(String resource) throws IOException {
Properties properties = new Properties();
InputStream in = ResultSetConverter.class.getResourceAsStream(resource);
properties.load(in);
in.close();
return properties;
}
private static Connection openConnection(Properties connectionProperties) throws IOException, SQLException {
String database = connectionProperties.getProperty("database");
String username = connectionProperties.getProperty("username");
String password = connectionProperties.getProperty("password");
return DriverManager.getConnection(database, username, password);
}
}
package com.oracle.jdbc;
import java.sql.*;
import java.text.*;
import java.util.*;
import com.google.common.base.CaseFormat;
public class QueryHelper {
static DateFormat DATE_FORMAT = new SimpleDateFormat("YYYY-MM-dd");
public static List<Map<String, Object>> select(Statement stmt, String query) throws SQLException {
ResultSet resultSet = stmt.executeQuery(query);
List<Map<String, Object>> records = mapRecords(resultSet);
resultSet.close();
return records;
}
public static List<Map<String, Object>> mapRecords(ResultSet resultSet) throws SQLException {
List<Map<String, Object>> records = new ArrayList<Map<String, Object>>();
ResultSetMetaData metaData = resultSet.getMetaData();
while (resultSet.next()) {
records.add(mapRecord(resultSet, metaData));
}
return records;
}
public static Map<String, Object> mapRecord(ResultSet resultSet, ResultSetMetaData metaData) throws SQLException {
Map<String, Object> record = new HashMap<String, Object>();
for (int c = 1; c <= metaData.getColumnCount(); c++) {
String columnType = metaData.getColumnTypeName(c);
String columnName = formatPropertyName(metaData.getColumnName(c));
Object value = resultSet.getObject(c);
if (columnType.equals("DATE")) {
value = DATE_FORMAT.format(value);
}
record.put(columnName, value);
}
return record;
}
private static String formatPropertyName(String property) {
return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, property);
}
}
driver=com.mysql.jdbc.Driver
database=jdbc:mysql://localhost/JDBC_Tutorial
username=root
password=
-- phpMyAdmin SQL Dump
-- version 4.5.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Jan 12, 2016 at 07:40 PM
-- Server version: 10.1.8-MariaDB
-- PHP Version: 5.6.14
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `jdbc_tutorial`
--
CREATE DATABASE IF NOT EXISTS `jdbc_tutorial` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `jdbc_tutorial`;
DELIMITER $$
--
-- Functions
--
DROP FUNCTION IF EXISTS `getAge`$$
CREATE DEFINER=`root`@`localhost` FUNCTION `getAge` (`in_dob` DATE) RETURNS INT(11) NO SQL
BEGIN
DECLARE l_age INT;
IF DATE_FORMAT(NOW(),'00-%m-%d') >= DATE_FORMAT(in_dob,'00-%m-%d') THEN
-- This person has had a birthday this year
SET l_age=DATE_FORMAT(NOW(),'%Y')-DATE_FORMAT(in_dob,'%Y');
ELSE
-- Yet to have a birthday this year
SET l_age=DATE_FORMAT(NOW(),'%Y')-DATE_FORMAT(in_dob,'%Y')-1;
END IF;
RETURN(l_age);
END$$
DELIMITER ;
-- --------------------------------------------------------
--
-- Table structure for table `beatles`
--
DROP TABLE IF EXISTS `beatles`;
CREATE TABLE IF NOT EXISTS `beatles` (
`id` int(11) NOT NULL,
`first_name` varchar(255) DEFAULT NULL,
`last_name` varchar(255) DEFAULT NULL,
`date_of_birth` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Truncate table before insert `beatles`
--
TRUNCATE TABLE `beatles`;
--
-- Dumping data for table `beatles`
--
INSERT INTO `beatles` (`id`, `first_name`, `last_name`, `date_of_birth`) VALUES(100, 'John', 'Lennon', '1940-10-09');
INSERT INTO `beatles` (`id`, `first_name`, `last_name`, `date_of_birth`) VALUES(101, 'Paul', 'McCartney', '1942-06-18');
INSERT INTO `beatles` (`id`, `first_name`, `last_name`, `date_of_birth`) VALUES(102, 'George', 'Harrison', '1943-02-25');
INSERT INTO `beatles` (`id`, `first_name`, `last_name`, `date_of_birth`) VALUES(103, 'Ringo', 'Starr', '1940-07-07');
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'application'
mainClassName = 'com.oracle.jdbc.QueryApp'
repositories {
maven {
url "http://repo1.maven.org/maven2"
}
}
jar {
baseName = 'jdbc-tutorial'
version = '1.0.0'
}
sourceCompatibility = 1.7
targetCompatibility = 1.7
dependencies {
compile 'mysql:mysql-connector-java:5.1.16'
compile 'com.google.guava:guava:18.0'
compile 'com.google.code.gson:gson:1.7.2'
}
task wrapper(type: Wrapper) {
gradleVersion = '2.9'
}
[
{
"firstName": "John",
"lastName": "Lennon",
"dateOfBirth": "1940-10-09",
"id": 100
},
{
"firstName": "Paul",
"lastName": "McCartney",
"dateOfBirth": "1942-06-18",
"id": 101
},
{
"firstName": "George",
"lastName": "Harrison",
"dateOfBirth": "1943-02-25",
"id": 102
},
{
"firstName": "Ringo",
"lastName": "Starr",
"dateOfBirth": "1940-07-07",
"id": 103
}
]
[
{
"firstName": "John",
"lastName": "Lennon",
"age": 75
},
{
"firstName": "Paul",
"lastName": "McCartney",
"age": 73
},
{
"firstName": "George",
"lastName": "Harrison",
"age": 72
},
{
"firstName": "Ringo",
"lastName": "Starr",
"age": 75
}
]
Commenting use_frameworks! in PodFile worked for me.
#use_frameworks!
Note: Did this on XCode 10.1, pod version 1.8.4
I know this has an accepted answer but if anyone comes upon this, my solution may help.
I found this question because I have a use-case where I wanted to turn off the :hover state for elements individually. Since there is no way to do this in the DOM, another good way to do it is to define a class in CSS that overrides the hover state.
For instance, the css:
.nohover:hover {
color: black !important;
}
Then with jQuery:
$("#elm").addClass("nohover");
With this method, you can override as many DOM elements as you would like without binding tons of onHover events.
let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.backgroundColor = .black
blurEffectView.alpha = 0.5
blurEffectView.frame = topView.bounds
if !self.presenting {
blurEffectView.frame.origin.x = 0
} else {
blurEffectView.frame.origin.x = -topView.frame.width
}
blurEffectView.frame.origin.x = -topView.frame.width
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
UIView.animate(withDuration: 0.2, delay: 0.0, options: [.curveEaseIn]) {
if !self.presenting {
blurEffectView.frame.origin.x = -topView.frame.width
} else {
blurEffectView.frame.origin.x = 0
}
view.addSubview(blurEffectView)
} completion: { (status) in
}
Try this...
1.Create libs folder:
2.Add .jar to libs folder:
3.Edit app's build.gradle dependency:
4.Sync project with Gradle files:
UPDATE:
Here I'm going to import org.eclipse.paho.client.mqttv3.jar file to our app module.
Happy coding...
I did not want to install visual studio and development environment, so I have installed AspNetMVC4Setup.exe in Windows server 2016 machine and it solved the problem. The installer was downloaded from Microsoft website.
I recommend Dowser. It is very easy to setup, and you need zero changes to your code. You can view counts of objects of each type through time, view list of live objects, view references to live objects, all from the simple web interface.
# memdebug.py
import cherrypy
import dowser
def start(port):
cherrypy.tree.mount(dowser.Root())
cherrypy.config.update({
'environment': 'embedded',
'server.socket_port': port
})
cherrypy.server.quickstart()
cherrypy.engine.start(blocking=False)
You import memdebug, and call memdebug.start. That's all.
I haven't tried PySizer or Heapy. I would appreciate others' reviews.
UPDATE
The above code is for CherryPy 2.X
, CherryPy 3.X
the server.quickstart
method has been removed and engine.start
does not take the blocking
flag. So if you are using CherryPy 3.X
# memdebug.py
import cherrypy
import dowser
def start(port):
cherrypy.tree.mount(dowser.Root())
cherrypy.config.update({
'environment': 'embedded',
'server.socket_port': port
})
cherrypy.engine.start()
In case .empty() doesn't work for you, which is for me
function SetDropDownToEmpty()
{
$('#dropdown').find('option').remove().end().append('<option value="0"></option>');
$("#dropdown").trigger("liszt:updated");
}
$(document).ready(
SetDropDownToEmpty() ;
)
It's a C trigraph. ??!
is |
, so ??!??!
is the operator ||
It's Ctrl+Shift+O / Cmd+Shift+O on mac. You can see it if you close all tabs
From Oracle docs, Date.toString() method convert Date object to a String of the specific form - do not use toString method on Date object. Try to use:
String stringDate = new SimpleDateFormat(YOUR_STRING_PATTERN).format(yourDateObject);
Next step is parse stringDate to Date:
Date date = new SimpleDateFormat(OUTPUT_PATTERN).parse(stringDate);
Note that, parse method throws ParseException
I want to output a table where each column has the smallest possible width,
where columns are padded with white space (but this can be changed) and rows are separated by newlines (but this can be changed) and where each item is formatted using str
(but...).
def ftable(tbl, pad=' ', sep='\n', normalize=str):
# normalize the content to the most useful data type
strtbl = [[normalize(it) for it in row] for row in tbl]
# next, for each column we compute the maximum width needed
w = [0 for _ in tbl[0]]
for row in strtbl:
for ncol, it in enumerate(row):
w[ncol] = max(w[ncol], len(it))
# a string is built iterating on the rows and the items of `strtbl`:
# items are prepended white space to an uniform column width
# formatted items are `join`ed using `pad` (by default " ")
# eventually we join the rows using newlines and return
return sep.join(pad.join(' '*(wid-len(it))+it for wid, it in zip(w, row))
for row in strtbl)
The function signature, ftable(tbl, pad=' ', sep='\n', normalize=str)
, with its default arguments is intended to
provide for maximum flexibility.
You can customize
pad='&', sep='\\\\\n'
to have the bulk of a LaTeX table)str
but if
you know that all your data is floating point lambda item:
"%.4f"%item
could be a reasonable choice, etc.Superficial testing:
I need some test data, possibly involving columns of different width so that the algorithm needs to be a little more sophisticated (but just a little bit;)
In [1]: from random import randrange
In [2]: table = [[randrange(10**randrange(10)) for i in range(5)] for j in range(3)]
In [3]: table
Out[3]:
[[974413992, 510, 0, 3114, 1],
[863242961, 0, 94924, 782, 34],
[1060993, 62, 26076, 75832, 833174]]
In [4]: print(ftable(table))
974413992 510 0 3114 1
863242961 0 94924 782 34
1060993 62 26076 75832 833174
In [5]: print(ftable(table, pad='|'))
974413992|510| 0| 3114| 1
863242961| 0|94924| 782| 34
1060993| 62|26076|75832|833174
You can change this in the page load
.
My intention is that when the page comes to the load
function, switch the links (the current link in the required one)
In this particular example, you can use:
#container:hover #cube {
background-color: yellow;
}
This example only works since cube
is a child of container
. For more complicated scenarios, you'd need to use different CSS, or use JavaScript.
Just add autofocus
in first input or textarea.
<input type="text" name="name" id="xax" autofocus="autofocus" />
You can now use CSS Grid to fix this.
<div class="outer">
<div class="top"> </div>
<div class="below"> </div>
</div>
And the css for this:
.outer {
display: grid;
grid-template: 1fr / 1fr;
place-items: center;
}
.outer > * {
grid-column: 1 / 1;
grid-row: 1 / 1;
}
.outer .below {
z-index: 2;
}
.outer .top {
z-index: 1;
}
For Java code, Create a POJO class for your object instead of a JSONObject. and use JSONEncapsulator for your POJO class. that way order of elements depends on the order of getter setters in your POJO class. for eg. POJO class will be like
Class myObj{
String userID;
String amount;
String success;
// getter setters in any order that you want
and where you need to send your json object in response
JSONContentEncapsulator<myObj> JSONObject = new JSONEncapsulator<myObj>("myObject");
JSONObject.setObject(myObj);
return Response.status(Status.OK).entity(JSONObject).build();
The response of this line will be
{myObject : {//attributes order same as getter setter order.}}
Tip for MULTIPLE VIDEOS on a page: I recently solved an issue with no mp4 playback in Chrome or Firefox (played fine in IE) in a page with 16 videos in modals (bootstrap 3) after discovering the frame rates of all the videos must be identical. I had 6 videos at 25fps and 12 at 29.97fps... after rendering all to 25fps versions, everything runs smooth across all browsers.
If using MySQL Workbench, simply look in the Session tab in the Information pane located in the sidebar.
Since C++17 you can use range-based for loops together with structured bindings for iterating over your map. This improves readability, as you reduce the amount of needed first
and second
members in your code:
std::map<std::string, std::pair<std::string, std::string>> myMap;
myMap["x"] = { "a", "b" };
myMap["y"] = { "c", "d" };
for (const auto &[k, v] : myMap)
std::cout << "m[" << k << "] = (" << v.first << ", " << v.second << ") " << std::endl;
Output:
m[x] = (a, b)
m[y] = (c, d)
Most of bootstrap datepickers as I write this answer are rather buggy when included in Bootstrap 4. In my view the least code adding solution is a jQuery plugin. I used this one https://plugins.jquery.com/datetimepicker/ - you can see its usage here: https://xdsoft.net/jqplugins/datetimepicker/ It sure is not as smooth as the whole BS interface, but it only requires its css and js files along with jQuery which is already included in bootstrap.
Just to clarify on OP's comment that the use on ref and out is a "reference to a value type or struct declared outside the method", which has already been established in incorrect.
Consider the use of ref on a StringBuilder, which is a reference type:
private void Nullify(StringBuilder sb, string message)
{
sb.Append(message);
sb = null;
}
// -- snip --
StringBuilder sb = new StringBuilder();
string message = "Hi Guy";
Nullify(sb, message);
System.Console.WriteLine(sb.ToString());
// Output
// Hi Guy
As apposed to this:
private void Nullify(ref StringBuilder sb, string message)
{
sb.Append(message);
sb = null;
}
// -- snip --
StringBuilder sb = new StringBuilder();
string message = "Hi Guy";
Nullify(ref sb, message);
System.Console.WriteLine(sb.ToString());
// Output
// NullReferenceException
CouchDB and MySQL are two very different beasts. JSON is the native way to store stuff in CouchDB. In MySQL, the best you could do is store JSON data as text in a single field. This would entirely defeat the purpose of storing it in an RDBMS and would greatly complicate every database transaction.
Don't.
Having said that, FriendFeed seemed to use an extremely custom schema on top of MySQL. It really depends on what exactly you want to store, there's hardly one definite answer on how to abuse a database system so it makes sense for you. Given that the article is very old and their main reason against Mongo and Couch was immaturity, I'd re-evaluate these two if MySQL doesn't cut it for you. They should have grown a lot by now.
You can get this issue if Apple update their terms. Simply log into your dev account and accept any updated terms and you should be good (you will need to goto Xcode -> project->signing and capabilities and retry the certificate check. This should get you going if terms are the issue.
Use the (ngModelChange)
event to detect changes on the model
You're almost there. Although I agree with @Alex Young answer about using props for that, you simply need a reference to the instance
before trying to spy on the method.
describe('my sweet test', () => {
it('clicks it', () => {
const app = shallow(<App />)
const instance = app.instance()
const spy = jest.spyOn(instance, 'myClickFunc')
instance.forceUpdate();
const p = app.find('.App-intro')
p.simulate('click')
expect(spy).toHaveBeenCalled()
})
})
Docs: http://airbnb.io/enzyme/docs/api/ShallowWrapper/instance.html
Following Code will work for "Inserting values into a SQL Server database using ado.net via C#"
// Your Connection string
string connectionString = "Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;";
// Collecting Values
string firstName="Name",
lastName="LastName",
userName="UserName",
password="123",
gender="Male",
contact="Contact";
int age=26;
// Query to be executed
string query = "Insert Into dbo.regist (FirstName, Lastname, Username, Password, Age, Gender,Contact) " +
"VALUES (@FN, @LN, @UN, @Pass, @Age, @Gender, @Contact) ";
// instance connection and command
using(SqlConnection cn = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(query, cn))
{
// add parameters and their values
cmd.Parameters.Add("@FN", System.Data.SqlDbType.NVarChar, 100).Value = firstName;
cmd.Parameters.Add("@LN", System.Data.SqlDbType.NVarChar, 100).Value = lastName;
cmd.Parameters.Add("@UN", System.Data.SqlDbType.NVarChar, 100).Value = userName;
cmd.Parameters.Add("@Pass", System.Data.SqlDbType.NVarChar, 100).Value = password;
cmd.Parameters.Add("@Age", System.Data.SqlDbType.Int).Value = age;
cmd.Parameters.Add("@Gender", System.Data.SqlDbType.NVarChar, 100).Value = gender;
cmd.Parameters.Add("@Contact", System.Data.SqlDbType.NVarChar, 100).Value = contact;
// open connection, execute command and close connection
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
Given a data setup like this:
The formula in cell D2 and copied down is:
=INDEX($B$2:$B$28,MATCH(1,INDEX(($A$2:$A$28=LARGE($A$2:$A$28,ROWS(D$1:D1)))*(COUNTIF(D$1:D1,$B$2:$B$28)=0),),0))
This formula will work even if there are tied OPS scores among players.
These two methods will help, assumming our week starts on Monday
/// <summary>
/// Returns the weekId
/// </summary>
/// <param name="DateTimeReference"></param>
/// <returns>Returns the current week id</returns>
public static DateTime GetDateFromWeek(int WeekReference)
{
//365 leap
int DaysOffset = 0;
if (WeekReference > 1)
{
DaysOffset = 7;
WeekReference = WeekReference - 1;
}
DateTime DT = new DateTime(DateTime.Now.Year, 1, 1);
int CurrentYear = DT.Year;
DateTime SelectedDateTime = DateTime.MinValue;
while (CurrentYear == DT.Year)
{
int TheWeek = WeekReportData.GetWeekId(DT);
if (TheWeek == WeekReference)
{
SelectedDateTime = DT;
break;
}
DT = DT.AddDays(1.0D);
}
if (SelectedDateTime == DateTime.MinValue)
{
throw new Exception("Please check week");
}
return SelectedDateTime.AddDays(DaysOffset);
}
/// <summary>
/// Returns the weekId
/// </summary>
/// <param name="DateTimeReference"></param>
/// <returns>Returns the current week id</returns>
public static int GetWeekId(DateTime DateTimeReference)
{
CultureInfo ciCurr = CultureInfo.InvariantCulture;
int weekNum = ciCurr.Calendar.GetWeekOfYear(DateTimeReference,
CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday);
return weekNum;
}