There is a solution to this if you really need a static access to the current context. In Startup.Configure(….)
app.Use(async (httpContext, next) =>
{
CallContext.LogicalSetData("CurrentContextKey", httpContext);
try
{
await next();
}
finally
{
CallContext.FreeNamedDataSlot("CurrentContextKey");
}
});
And when you need it you can get it with :
HttpContext context = CallContext.LogicalGetData("CurrentContextKey") as HttpContext;
I hope that helps. Keep in mind this workaround is when you don’t have a choice. The best practice is to use de dependency injection.
I tried this tool and it gave me good results.
You can use JavaScript Timing Events to call function after certain interval of time:
This shows the alert box after 3 seconds:
setInterval(function(){alert("Hello")},3000);
You can use two method of time event in javascript.i.e.
setInterval()
: executes a function, over and over again, at
specified time intervalssetTimeout()
: executes a function, once, after waiting a
specified number of millisecondsUse this extension for chrome. Allows to you request any site with ajax from any source. Adds to response 'Allow-Control-Allow-Origin: *' header
Personal preference really. You could use const when, as you say, it will not be re-assigned and is constant. For example if you wanted to assign your birthday. Your birthday never changes so you could use it as a constant. But your age does change so that could be a variable.
Use format
method with a specific pattern to extract the time.
Working example
var myDate = "2017-08-30T14:24:03";_x000D_
console.log(moment(myDate).format("HH:mm")); // 24 hour format_x000D_
console.log(moment(myDate).format("hh:mm a")); // use 'A' for uppercase AM/PM_x000D_
console.log(moment(myDate).format("hh:mm:ss A")); // with milliseconds
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
I've had success using this in response to a button click, so I guess that you can use it too after updating your contents:
myListView.smoothScrollToPosition(theListAdapter.getCount() -1);
n
in name
.I
(capital i).vendor_
. Note: It will only update the screen in the first line - until Esc is pressed (6.), at which point all lines will be updated.An uppercase I
must be used rather than a lowercase i
, because the lowercase i
is interpreted as the start of a text object, which is rather useful on its own, e.g. for selecting inside a tag block (it
):
Below code works for me in Angular 4
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
export class RegisterComponent implements OnInit {
registerForm: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.registerForm = this.formBuilder.group({
empname: [''],
empemail: ['']
});
}
onRegister(){
//sending data to server using http request
this.registerForm.reset()
}
}
The best way to go to the last line of the file is with G
. This will move the cursor to the last line of the file.
The best way to go to the last column in the line is with $
. This will move the cursor to the last column of the current line.
So just by doing G$
you get to the end of the file and the last line.
And if you want to enter insert mode at the end of the file then you just do GA
. By doing this you go to the last line of the file, and enter insert mode by appending to the last column. :)
I found the below code on below link... and it worked Select folder dialog WPF
using Microsoft.WindowsAPICodePack.Dialogs;
var dlg = new CommonOpenFileDialog();
dlg.Title = "My Title";
dlg.IsFolderPicker = true;
dlg.InitialDirectory = currentDirectory;
dlg.AddToMostRecentlyUsedList = false;
dlg.AllowNonFileSystemItems = false;
dlg.DefaultDirectory = currentDirectory;
dlg.EnsureFileExists = true;
dlg.EnsurePathExists = true;
dlg.EnsureReadOnly = false;
dlg.EnsureValidNames = true;
dlg.Multiselect = false;
dlg.ShowPlacesList = true;
if (dlg.ShowDialog() == CommonFileDialogResult.Ok)
{
var folder = dlg.FileName;
// Do something with selected folder string
}
updated on May 26-2018
If the external library is in a folder that is under the project then
File -> Settings -> Project -> Project structure -> select the folder and Mark as Sources!
If not, add content root, and do similar things.
Underline to multiple strings in a sentence.
extension UILabel {
func underlineMyText(range1:String, range2:String) {
if let textString = self.text {
let str = NSString(string: textString)
let firstRange = str.range(of: range1)
let secRange = str.range(of: range2)
let attributedString = NSMutableAttributedString(string: textString)
attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: firstRange)
attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: secRange)
attributedText = attributedString
}
}
}
Use by this way.
lbl.text = "By continuing you agree to our Terms of Service and Privacy Policy."
lbl.underlineMyText(range1: "Terms of Service", range2: "Privacy Policy.")
Verifying Clint's awesome and correct answer from above:
The performance between the two queries below is interesting. 52% being the top one. And 48% being the second one. A 4% improvement in performance using DISTINCT instead of ORDER BY. But ORDER BY has the advantage to sort by multiple columns.
IF (OBJECT_ID('tempdb..#DocumentStatusLogs') IS NOT NULL) BEGIN DROP TABLE #DocumentStatusLogs END
CREATE TABLE #DocumentStatusLogs (
[ID] int NOT NULL,
[DocumentID] int NOT NULL,
[Status] varchar(20),
[DateCreated] datetime
)
INSERT INTO #DocumentStatusLogs([ID], [DocumentID], [Status], [DateCreated]) VALUES (2, 1, 'S1', '7/29/2011 1:00:00')
INSERT INTO #DocumentStatusLogs([ID], [DocumentID], [Status], [DateCreated]) VALUES (3, 1, 'S2', '7/30/2011 2:00:00')
INSERT INTO #DocumentStatusLogs([ID], [DocumentID], [Status], [DateCreated]) VALUES (6, 1, 'S1', '8/02/2011 3:00:00')
INSERT INTO #DocumentStatusLogs([ID], [DocumentID], [Status], [DateCreated]) VALUES (1, 2, 'S1', '7/28/2011 4:00:00')
INSERT INTO #DocumentStatusLogs([ID], [DocumentID], [Status], [DateCreated]) VALUES (4, 2, 'S2', '7/30/2011 5:00:00')
INSERT INTO #DocumentStatusLogs([ID], [DocumentID], [Status], [DateCreated]) VALUES (5, 2, 'S3', '8/01/2011 6:00:00')
INSERT INTO #DocumentStatusLogs([ID], [DocumentID], [Status], [DateCreated]) VALUES (6, 3, 'S1', '8/02/2011 7:00:00')
Option 1:
SELECT
[Extent1].[ID],
[Extent1].[DocumentID],
[Extent1].[Status],
[Extent1].[DateCreated]
FROM #DocumentStatusLogs AS [Extent1]
OUTER APPLY (
SELECT TOP 1
[Extent2].[ID],
[Extent2].[DocumentID],
[Extent2].[Status],
[Extent2].[DateCreated]
FROM #DocumentStatusLogs AS [Extent2]
WHERE [Extent1].[DocumentID] = [Extent2].[DocumentID]
ORDER BY [Extent2].[DateCreated] DESC, [Extent2].[ID] DESC
) AS [Project2]
WHERE ([Project2].[ID] IS NULL OR [Project2].[ID] = [Extent1].[ID])
Option 2:
SELECT
[Limit1].[DocumentID] AS [ID],
[Limit1].[DocumentID] AS [DocumentID],
[Limit1].[Status] AS [Status],
[Limit1].[DateCreated] AS [DateCreated]
FROM (
SELECT DISTINCT [Extent1].[DocumentID] AS [DocumentID] FROM #DocumentStatusLogs AS [Extent1]
) AS [Distinct1]
OUTER APPLY (
SELECT TOP (1) [Project2].[ID] AS [ID], [Project2].[DocumentID] AS [DocumentID], [Project2].[Status] AS [Status], [Project2].[DateCreated] AS [DateCreated]
FROM (
SELECT
[Extent2].[ID] AS [ID],
[Extent2].[DocumentID] AS [DocumentID],
[Extent2].[Status] AS [Status],
[Extent2].[DateCreated] AS [DateCreated]
FROM #DocumentStatusLogs AS [Extent2]
WHERE [Distinct1].[DocumentID] = [Extent2].[DocumentID]
) AS [Project2]
ORDER BY [Project2].[ID] DESC
) AS [Limit1]
M$'s Management Studio: After highlighting and running the first block, highlight both Option 1 and Option 2, Right click -> [Display Estimated Execution Plan]. Then run the entire thing to see the results.
Option 1 Results:
ID DocumentID Status DateCreated
6 1 S1 8/2/11 3:00
5 2 S3 8/1/11 6:00
6 3 S1 8/2/11 7:00
Option 2 Results:
ID DocumentID Status DateCreated
6 1 S1 8/2/11 3:00
5 2 S3 8/1/11 6:00
6 3 S1 8/2/11 7:00
Note:
I tend to use APPLY when I want a join to be 1-to-(1 of many).
I use a JOIN if I want the join to be 1-to-many, or many-to-many.
I avoid CTE with ROW_NUMBER() unless I need to do something advanced and am ok with the windowing performance penalty.
I also avoid EXISTS / IN subqueries in the WHERE or ON clause, as I have experienced this causing some terrible execution plans. But mileage varies. Review the execution plan and profile performance where and when needed!
Should be easy to find in the javadocs...
byte[] byteArr = new byte[] { 0xC, 0xA, 0xF, 0xE };
InputStream is = new ByteArrayInputStream(byteArr);
public class WeatherResponse {
private int cod;
private String base;
private Weather main;
public int getCod(){
return this.cod;
}
public void setCod(int cod){
this.cod = cod;
}
public String getBase(){
return base;
}
public void setBase(String base){
this.base = base;
}
public Weather getWeather() {
return main;
}
// default constructor, getters and setters
}
public class Weather {
private int id;
private String main;
private String description;
public String getMain(){
return main;
}
public void setMain(String main){
this.main = main;
}
public String getDescription(){
return description;
}
public void setDescription(String description){
this.description = description;
}
// default constructor, getters and setters
}
// accessing methods
// success!
Log.i("App", weatherResponse.getBase());
Log.i("App", weatherResponse.getWeather().getMain());
Log.i("App", weatherResponse.getWeather().getDescription());
import tkinter as tk
...
x = tk.Label(text='Hello', visible=True)
def visiblelabel(lb, visible):
lb.config(visible=visible)
visiblelabel(x, False) # Hide
visiblelabel(x, True) # Show
P.S. config
can change any attribute:
x.config(text='Hello') # Text: Hello
x.config(text='Bye', font=('Arial', 20, 'bold')) # Text: Bye, Font: Arial Bold 20
x.config(bg='red', fg='white') # Background: red, Foreground: white
It's a bypass of StringVar
, IntVar
etc.
String input = "some input string";
int hashCode = input.hashCode();
System.out.println("input hash code = " + hashCode);
Note that there is no variable interpolation in Java. Variable interpolation is variable substitution with its value inside a string. An example in Ruby:
#!/usr/bin/ruby
age = 34
name = "William"
puts "#{name} is #{age} years old"
The Ruby interpreter automatically replaces variables with its values inside a string. The fact, that we are going to do interpolation is hinted by sigil characters. In Ruby, it is #{}. In Perl, it could be $, % or @. Java would only print such characters, it would not expand them.
Variable interpolation is not supported in Java. Instead of this, we have string formatting.
package com.zetcode;
public class StringFormatting
{
public static void main(String[] args)
{
int age = 34;
String name = "William";
String output = String.format("%s is %d years old.", name, age);
System.out.println(output);
}
}
In Java, we build a new string using the String.format() method. The outcome is the same, but the methods are different.
See http://en.wikipedia.org/wiki/Variable_interpolation
Edit As of 2019, JEP 326 (Raw String Literals) was withdrawn and superseded by multiple JEPs eventually leading to JEP 378: Text Blocks delivered in Java 15.
A text block is a multi-line string literal that avoids the need for most escape sequences, automatically formats the string in a predictable way, and gives the developer control over the format when desired.
However, still no string interpolation:
Non-Goals: … Text blocks do not directly support string interpolation. Interpolation may be considered in a future JEP. In the meantime, the new instance method
String::formatted
aids in situations where interpolation might be desired.
If you can do the construction in a single operation, then something like the vstack-with-fancy-indexing answer is a fine approach. But if your condition is more complicated or your rows come in on the fly, you may want to grow the array. In fact the numpythonic way to do something like this - dynamically grow an array - is to dynamically grow a list:
A = np.array([[1,2,3],[4,5,6]])
Alist = [r for r in A]
for i in range(100):
newrow = np.arange(3)+i
if i%5:
Alist.append(newrow)
A = np.array(Alist)
del Alist
Lists are highly optimized for this kind of access pattern; you don't have convenient numpy multidimensional indexing while in list form, but for as long as you're appending it's hard to do better than a list of row arrays.
Under normal circumstances,out of bound of array when you encounter the error. So,check uo your array subscript.
The problem is that HTML doesn't recognize the escape character. You could work around that by using the single quotes for the HTML attribute and the double quotes for the onclick.
<a href="#" onclick='DoEdit("Preliminary Assessment \"Mini\""); return false;'>edit</a>
I generally like to use my own extension for that:
string data = "THExxQUICKxxBROWNxxFOX";
var dataspt = data.Split("xx");
//>THE QUICK BROWN FOX
//the extension class must be declared as static
public static class StringExtension
{
public static string[] Split(this string str, string splitter)
{
return str.Split(new[] { splitter }, StringSplitOptions.None);
}
}
This will however lead to an Exception, if Microsoft decides to include this method-overload in later versions. It is also the likely reason why Microsoft has not included this method in the meantime: At least one company I worked for, used such an extension in all their C# projects.
It may also be possible to conditionally define the method at runtime if it doesn't exist.
If you have to run composer with sudo, you should change the directory of composer to
/usr/bin
this was tested on Centos8.
1. About @Component
@Component functs similarily to @Configuration.
They both indicate that the annotated class has one or more beans need to be registered to Spring-IOC-Container
.
The class annotated by @Component, we call it Component of Spring
. It is a concept that contains several beans.
Component class
needs to be auto-scanned by Spring for registering those beans of the component class
.
2. About @Bean
@Bean is used to annotate the method of component-class
(as mentioned above). It indicate the instance retured by the annotated method needs to be registered to Spring-IOC-Container
.
3. Conclusion
The difference between them two is relatively obivious, they are used in different circumstances
.
The general usage is:
// @Configuration is implemented by @Component
@Configuration
public ComponentClass {
@Bean
public FirstBean FirstBeanMethod() {
return new FirstBean();
}
@Bean
public SecondBean SecondBeanMethod() {
return new SecondBean();
}
}
Yes this is possible, however not convenient as Jens said. Using Next generation load balancers like Alteon, which Uses a proprietary protocol called DSSP(Distributed site state Protocol) which performs regular site checks to make sure that the service is available both Locally or Globally i.e different geographical areas. You need to however in your Master DNS to delegate the URL or Service to the device by configuring it as an Authoritative Name Server for that IP or Service. By doing this, the device answers DNS queries where it will resolve the IP that has a service by Round-Robin or is not congested according to how you have chosen from several metrics.
import os
exec_filepath = os.path.realpath(__file__)
exec_dirpath = exec_filepath[0:len(exec_filepath)-len(os.path.basename(__file__))]
I ran into a similar problem. Simply moving my tsconfig.json from the root of my project up to a different scope helped. In my project, I moved tsconfig.json from the root up to wwwroot.
Yes, if you use the proper generic type signature for the outer hashmap.
HashMap<String, HashMap<String, Foo>> hm = new HashMap<String, HashMap<String, Foobar>>();
// populate the map
hm.get("keyname").get("nestedkeyname");
If you're not using generics, you'd have to do a cast to convert the object retrieved from the outer hash map to a HashMap
(or at least a Map
) before you could call its get()
method. But you should be using generics ;-)
You are getting Floating point exception because Number % i
, when i
is 0
:
int Is_Prime( int Number ){
int i ;
for( i = 0 ; i < Number / 2 ; i++ ){
if( Number % i != 0 ) return -1 ;
}
return Number ;
}
Just start the loop at i = 2
. Since i = 1
in Number % i
it always be equal to zero, since Number is a int.
First add permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
using Bitmap from resources
Bitmap b =BitmapFactory.decodeResource(getResources(),R.drawable.userimage);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(), b, "Title", null);
Uri imageUri = Uri.parse(path);
share.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(share, "Select"));
Tested via bluetooth and other messengers
JPA will use all properties of the class, unless you specifically mark them with @Transient
:
@Transient
private String agencyName;
The @Column
annotation is purely optional, and is there to let you override the auto-generated column name. Furthermore, the length
attribute of @Column
is only used when auto-generating table definitions, it has no effect on the runtime.
You can consider to replace default WordPress jQuery script with Google Library by adding something like the following into theme functions.php file:
function modify_jquery() {
if (!is_admin()) {
wp_deregister_script('jquery');
wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', false, '1.10.2');
wp_enqueue_script('jquery');
}
}
add_action('init', 'modify_jquery');
Code taken from here: http://www.wpbeginner.com/wp-themes/replace-default-wordpress-jquery-script-with-google-library/
And now a keys iterator for range-based for loop.
template<typename C>
class keys_it
{
typename C::const_iterator it_;
public:
using key_type = typename C::key_type;
using pointer = typename C::key_type*;
using difference_type = std::ptrdiff_t;
keys_it(const typename C::const_iterator & it) : it_(it) {}
keys_it operator++(int ) /* postfix */ { return it_++ ; }
keys_it& operator++( ) /* prefix */ { ++it_; return *this ; }
const key_type& operator* ( ) const { return it_->first ; }
const key_type& operator->( ) const { return it_->first ; }
keys_it operator+ (difference_type v ) const { return it_ + v ; }
bool operator==(const keys_it& rhs) const { return it_ == rhs.it_; }
bool operator!=(const keys_it& rhs) const { return it_ != rhs.it_; }
};
template<typename C>
class keys_impl
{
const C & c;
public:
keys_impl(const C & container) : c(container) {}
const keys_it<C> begin() const { return keys_it<C>(std::begin(c)); }
const keys_it<C> end () const { return keys_it<C>(std::end (c)); }
};
template<typename C>
keys_impl<C> keys(const C & container) { return keys_impl<C>(container); }
Usage:
std::map<std::string,int> my_map;
// fill my_map
for (const std::string & k : keys(my_map))
{
// do things
}
That's what i was looking for. But nobody had it, it seems.
You get my OCD code alignment as a bonus.
As an exercise, write your own for values(my_map)
After Pulling hair for a long time,I finally found an issue.I've selected wrong certificate while creating Provisioning Profile,By selecting right one,It helped for me.In your case,If it is multiple then You have to try and select one by one to get this issue solved.
As the accepted answer has two important shortfalls, I'm posting the improved answer for those new comers who are looking for a correct answer:
foreach (array_filter(glob('/Path/To/*'), 'is_file') as $file)
{
// Do something with $file
}
globe
function results with is_file
is necessary, because it might return some directories as well..
in their names, so */*
pattern sucks in general.As @Ian explained, the problem is that jQuery's click()
is not the same as the native one.
Therefore, consider using vanilla-js instead of jQuery:
var a = document.createElement('a');
a.href = "img.png";
a.download = "output.png";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
T-SQL and others;
select * from t where year(Columnx) = 2010
The below css code always keep the button at the bottom of the page
position:absolute;
bottom:0;
Since you want to do it in relative positioning, you should go for margin-top:100%
position:relative;
margin-top:100%;
EDIT1: JSFiddle1
EDIT2: To place button at center of the screen,
position:relative;
left: 50%;
margin-top:50%;
As noted by jitter, the $.ajax
function serializes any object/array used as the data
parameter into a url-encoded format. Oddly enough, the dataType
parameter only applies to the response from the server - and not to any data in the request.
After encountering the same problem I downloaded and used the jquery-json plugin to correctly encode the request data to the ScriptService. Then, used the $.toJSON
function to encode the desired arguments to send to the server:
$.ajax({
type: "POST",
url: "EditUserProfile.aspx/DeleteRecord",
data: $.toJSON(obj),
contentType: "application/json; charset=utf-8",
dataType: "json"
....
});
var table = document.getElementById("someTableID");
var totalRows = document.getElementById("someTableID").rows.length;
var totalCol = 3; // enter the number of columns in the table minus 1 (first column is 0 not 1)
//To display all values
for (var x = 0; x <= totalRows; x++)
{
for (var y = 0; y <= totalCol; y++)
{
alert(table.rows[x].cells[y].innerHTML;
}
}
//To display a single cell value enter in the row number and column number under rows and cells below:
var firstCell = table.rows[0].cells[0].innerHTML;
alert(firstCell);
//Note: if you use <th> this will be row 0, so your data will start at row 1 col 0
The free version of TightVnc viewer (I have TightVnc Viewer 1.5.4 8/3/2011) build does not support this. What you need is RealVNC but VNC Enterprise Edition 4.2 or the Personal Edition. Unfortunately this is not free and you have to pay for a license.
From the RealVNC website [releasenote] http://www.realvnc.com/products/enterprise/4.2/release-notes.html
VNC Viewer: Full-screen mode can span monitors on a multi-monitor system.
Laravel provides bunch of helper functions and for your requirement you can simply
use url() function of Laravel Helpers
but in case of Laravel 5.2 you will have to use url('/')
here is the list of all other helper functions of Laravel
As the question is asked years ago, and Android is evolved a lot on this URI scheme.
From original URI scheme, to deep link, and now Android App Links.
Android now recommends to use HTTP URLs, not define your own URI scheme. Because Android App Links use HTTP URLs that link to a website domain you own, so no other app can use your links. You can check the comparison of deep link and Android App links from here
Now you can easily add a URI scheme by using Android Studio option: Tools > App Links Assistant. Please refer the detail to Android document: https://developer.android.com/studio/write/app-link-indexing.html
Since maven-surefire-plugin does not run Suite class first but treats suite and test classes same, so we can configure plugin as below to enable only suite classes and disable all the tests. Suite will run all the tests.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.5</version>
<configuration>
<includes>
<include>**/*Suite.java</include>
</includes>
<excludes>
<exclude>**/*Test.java</exclude>
<exclude>**/*Tests.java</exclude>
</excludes>
</configuration>
</plugin>
Well you can hide the close button by changing the FormBorderStyle from the properties section or programmatically in the constructor using:
public Form1()
{
InitializeComponent();
this.FormBorderStyle = FormBorderStyle.None;
}
then you create a menu strip item to exit the application.
cheers
You'll need at least PHP Version 5.4 to implement this solution without exploding into a variable on one line and concatenating on the next, but an easy one liner would be:
$_SERVER["HTTP_HOST"].explode('?', $_SERVER["REQUEST_URI"], 2)[0];
Server Variables: http://php.net/manual/en/reserved.variables.server.php
Array Dereferencing: https://wiki.php.net/rfc/functionarraydereferencing
Those are just version designations (just like windows xp, vista or windows 7) which they are using to name their major releases, instead of using version numbers. so you'll want to use the newest eclipse version available, which is helios (or 3.6 which is the corresponding version number).
As you are dealing with a string array, have you considered Join?
If Len(Join(FileNamesList)) > 0 Then
If you load a 32 bit version of your dll with a 64 bit JRE you could have this issue. This was my case.
#1)
print " ".join(map(chr, range(ord('a'),ord('n')+1)))
#2)
print " ".join(map(chr, range(ord('a'),ord('n')+1,2)))
#3)
urls = ["hello.com/", "hej.com/", "hallo.com/"]
an = map(chr, range(ord('a'),ord('n')+1))
print [ x + y for x,y in zip(urls, an)]
After version 2.23
, Git has introduced the git restore
command which you can use to do that. Quoting the official documentation:
Restore specified paths in the working tree with some contents from a restore source. If a path is tracked but does not exist in the restore source, it will be removed to match the source.
The command can also be used to restore the content in the index with
--staged
, or restore both the working tree and the index with--staged --worktree
.
So you can invoke git restore --staged <path>
and unstage the file but also keep the changes you made. Remember that if the file was not staged you lose all the changes you made to it.
I had a similar situation: multiple developers using the same private key, but I couldn't find mine anymore after upgrade to Lion. The very simple fix was to export the private key for the specific certificate (in my case the Development cert) from the other machine, move it to my computer and drag it into keychain access there. Xcode immediately picked it up and I was good to go.
This work for me
$('#mySelect option:contains(' + value + ')').attr('selected', 'selected');
If you want to clear the data but keep the headers:
$('#myTableId tbody').empty();
The table must be formatted in this manner:
<table id="myTableId">
<thead>
<tr>
<th>header1</th><th>header2</th>
</tr>
</thead>
<tbody>
<tr>
<td>data1</td><td>data2</td>
</tr>
</tbody>
</table>
I found this issue addressed here vagrant issues. Two ways to do it:
Run this on guest (i.e. after you ssh into vbox via vagrant ssh
)
sudo ln -s /opt/VBoxGuestAdditions-4.3.10/lib/VBoxGuestAdditions /usr/lib/VBoxGuestAdditions
Then run vagrant reload
to correctly mount the folders.
As @klang pointed out, update the VBoxGuestAdditions.iso file on your mac:
wget https://www.virtualbox.org/download/testcase/VBoxGuestAdditions_4.3.11-93070.iso??
sudo cp VBoxGuestAdditions_4.3.11-93070.iso /Applications/VirtualBox.app/Contents/MacOS/VBoxGuestAdditions.iso
Since the iso is no longer available, you can use the 4.3.12 one (http://dlc.sun.com.edgesuite.net/virtualbox/4.3.12/VBoxGuestAdditions_4.3.12.iso)
note : the binary vbox4.3.12 for os X is not available at this time
You can't instantiate a date object any way you want. It has to be in a specific way. Here are some valid examples:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
or
d1 = new Date("October 13, 1975 11:13:00")
d2 = new Date(79,5,24)
d3 = new Date(79,5,24,11,33,0)
Chrome must just be more flexible.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
From apsillers comment:
the EMCAScript specification requires exactly one date format (i.e., YYYY-MM-DDTHH:mm:ss.sssZ) but custom date formats may be freely supported by an implementation: "If the String does not conform to that [ECMAScript-defined] format the function may fall back to any implementation-specific heuristics or implementation-specific date formats." Chrome and FF simply have different "implementation-specific date formats."
none of these methods worked for me, so I just solved this with CSS:
.upvotes:before {
content:"";
float: left;
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
}
If you do an "Add" it will add it to the bottom of the list. You need to do an "Insert" if you want the item added to the top of the list.
This rule
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o producer.o consumer.o AddRemove.o
is wrong. It says to create a file named producer.o (with -o producer.o
), but you want to create a file named main
. Please excuse the shouting, but ALWAYS USE $@ TO REFERENCE THE TARGET:
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o $@ producer.o consumer.o AddRemove.o
As Shahbaz rightly points out, the gmake professionals would also use $^
which expands to all the prerequisites in the rule. In general, if you find yourself repeating a string or name, you're doing it wrong and should use a variable, whether one of the built-ins or one you create.
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o $@ $^
This problem can also come up when you don't have your constructor immediately call super.
So this will work:
public Employee(String name, String number, Date date)
{
super(....)
}
But this won't:
public Employee(String name, String number, Date date)
{
// an example of *any* code running before you call super.
if (number < 5)
{
number++;
}
super(....)
}
The reason the 2nd example fails is because java is trying to implicitely call
super(name,number,date)
as the first line in your constructor.... So java doesn't see that you've got a call to super going on later in the constructor. It essentially tries to do this:
public Employee(String name, String number, Date date)
{
super(name, number, date);
if (number < 5)
{
number++;
}
super(....)
}
So the solution is pretty easy... Just don't put code before your super call ;-) If you need to initialize something before the call to super, do it in another constructor, and then call the old constructor... Like in this example pulled from this StackOverflow post:
public class Foo
{
private int x;
public Foo()
{
this(1);
}
public Foo(int x)
{
this.x = x;
}
}
I think this solve the problem :
boolean allOk = false;
try{
q();
allOk = true;
} finally {
try {
is.close();
} catch (Exception e) {
if(allOk) {
throw new SomeException(e);
}
}
}
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; ++i) {
// ...
}
This should do the trick:
$($.parseJSON(data.msg)).map(function () {
return $('<option>').val(this.value).text(this.label);
}).appendTo('#combobox');
Here's the distinction between ajax
and getJSON
(from the jQuery documentation):
[getJSON] is a shorthand Ajax function, which is equivalent to:
$.ajax({ url: url, dataType: 'json', data: data, success: callback });
EDIT: To be clear, part of the problem was that the server's response was returning a json object that looked like this:
{
"msg": '[{"value":"1","label":"xyz"}, {"value":"2","label":"abc"}]'
}
...So that msg
property needed to be parsed manually using $.parseJSON()
.
Java Function to bring Linux Command Result!
public String RunLinuxCommand(String cmd) throws IOException {
String linuxCommandResult = "";
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
try {
while ((linuxCommandResult = stdInput.readLine()) != null) {
return linuxCommandResult;
}
while ((linuxCommandResult = stdError.readLine()) != null) {
return "";
}
} catch (Exception e) {
return "";
}
return linuxCommandResult;
}
This is a warning related to the fact that most JavaScript frameworks (jQuery, Angular, YUI, Bootstrap...) offer backward support for old-nasty-most-hated Internet Explorer starting from IE8 down to IE6 :/
One day that backward compatibility support will be dropped (for IE8/7/6 since IE9 deals with it), and you will no more see this warning (and other IEish bugs)..
It's a question of time (now IE8 has 10% worldwide share, once it reaches 1% it is DEAD), meanwhile, just ignore the warning and stay zen :)
For ListBox / DropDown in MVC5 - i've found this to work for me sofar:
in Model:
[Required(ErrorMessage = "- Select item -")]
public List<string> SelectedItem { get; set; }
public List<SelectListItem> AvailableItemsList { get; set; }
in View:
@Html.ListBoxFor(model => model.SelectedItem, Model.AvailableItemsList)
@Html.ValidationMessageFor(model => model.SelectedItem, "", new { @class = "text-danger" })
It is likely because they used a single function for escaping attributes and text nodes. &
doesn't do any harm so why complicate your code and make it more error-prone by having two escaping functions and having to pick between them?
Why make it so complicated? You can use this instead:
import UIKit
let PI = 3.14159265359
round( PI ) // 3.0 rounded to the nearest decimal
round( PI * 100 ) / 100 //3.14 rounded to the nearest hundredth
round( PI * 1000 ) / 1000 // 3.142 rounded to the nearest thousandth
See it work in Playground.
PS: Solution from: http://rrike.sh/xcode/rounding-various-decimal-places-swift/
I think this works, at least partially (have not investigated):
nvm uninstall <VERSION_TO_UNINSTALL>
eg:
nvm uninstall 4.4.5
You simply need to do a SUBSTR on the string in col3....
Select col1, col2, REPLACE(substr(col3, instr(col3, 'Client Name'),
(instr(col3, '|', instr(col3, 'Client Name') -
instr(col3, 'Client Name'))
),
'Client Name = ',
'')
from Table01
And yes, that is a bad DB design for the reasons stated in the original issue
What about this one :
<DockPanel Margin="8">
<Border CornerRadius="6" BorderBrush="Gray" Background="LightGray" BorderThickness="2" DockPanel.Dock="Top">
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="14" Padding="0 0 8 0" HorizontalAlignment="Center" VerticalAlignment="Center">Search:</TextBlock>
<TextBox x:Name="txtSearchTerm" HorizontalAlignment="Center" VerticalAlignment="Center" />
<Image Source="lock.png" Width="32" Height="32" HorizontalAlignment="Center" VerticalAlignment="Center" />
</StackPanel>
</Border>
<StackPanel Orientation="Horizontal" DockPanel.Dock="Bottom" Height="25" />
</DockPanel>
The video quality depends upon the Connection speed using API
alternatively for other than API means without YouTube app you can follow this link
If you're already using Underscore, use _.find()
_.find(yourList, function (item) {
return item.id === 1;
});
The best bet with these types of questions is to see exactly what python does. The dis
module is incredibly informative:
>>> import dis
>>> dis.dis("val != None")
1 0 LOAD_NAME 0 (val)
2 LOAD_CONST 0 (None)
4 COMPARE_OP 3 (!=)
6 RETURN_VALUE
>>> dis.dis("not (val is None)")
1 0 LOAD_NAME 0 (val)
2 LOAD_CONST 0 (None)
4 COMPARE_OP 9 (is not)
6 RETURN_VALUE
>>> dis.dis("val is not None")
1 0 LOAD_NAME 0 (val)
2 LOAD_CONST 0 (None)
4 COMPARE_OP 9 (is not)
6 RETURN_VALUE
Notice that the last two cases reduce to the same sequence of operations, Python reads not (val is None)
and uses the is not
operator. The first uses the !=
operator when comparing with None
.
As pointed out by other answers, using !=
when comparing with None
is a bad idea.
I had this problem, but not via the Header. My placeholder was in the body. So I replaced all the <%=
with <%#
and did
protected void Page_Load(object sender, EventArgs e)
{
Page.Header.DataBind();
}
and it worked.
brilliant example Jonathan Leffler, to make your code work on SLES, I needed to add an additional header to allow the pid_t object :)
#include <sys/types.h>
When you create a repository in bitbucket.org, it gives you instructions on how to set up your local directory. Chances are, you just forgot to run the code:
git remote add origin https://[email protected]/username/reponame.git
In the connection properties window I changed my selection from "SID" to "Service Name", and copied my SID into the Service Name field. No idea why this change happened or why it worked, but it got me back on Oracle.
You can also use named arguments which are optional and can be given in any order.
Set namedArguments = WScript.Arguments.Named
Here's a little helper function:
Function GetNamedArgument(ByVal argumentName, ByVal defaultValue)
If WScript.Arguments.Named.Exists(argumentName) Then
GetNamedArgument = WScript.Arguments.Named.Item(argumentName)
Else
GetNamedArgument = defaultValue
End If
End Function
Example VBS:
'[test.vbs]
testArg = GetNamedArgument("testArg", "-unknown-")
wscript.Echo now &": "& testArg
Example Usage:
test.vbs /testArg:123
in Bootstrap 5 you can do something like this:
<div class="py-2 my-1 text-center position-relative mx-2">
<div class="position-absolute w-100 top-50 start-50 translate-middle" style="z-index: 2">
<span class="d-inline-block bg-white px-2 text-muted">or</span>
</div>
<div class="position-absolute w-100 top-50 start-0 border-muted border-top"></div>
</div>
If you don't want to use dateutil, you can try this function:
def from_utc(utcTime,fmt="%Y-%m-%dT%H:%M:%S.%fZ"):
"""
Convert UTC time string to time.struct_time
"""
# change datetime.datetime to time, return time.struct_time type
return datetime.datetime.strptime(utcTime, fmt)
Test:
from_utc("2007-03-04T21:08:12.123Z")
Result:
datetime.datetime(2007, 3, 4, 21, 8, 12, 123000)
Adding this first conditional should work:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode != RESULT_CANCELED){
if (requestCode == CAMERA_REQUEST) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}
Depends how much you like the linq query syntax, you can use the extension methods directly like:
var item = Items.First(i => i.Id == 123);
And if you don't want to throw an error if the list is empty, use FirstOrDefault
which returns the default value for the element type (null
for reference types):
var item = Items.FirstOrDefault(i => i.Id == 123);
if (item != null)
{
// found it
}
Single()
and SingleOrDefault()
can also be used, but if you are reading from a database or something that already guarantees uniqueness I wouldn't bother as it has to scan the list to see if there's any duplicates and throws. First()
and FirstOrDefault()
stop on the first match, so they are more efficient.
Of the First()
and Single()
family, here's where they throw:
First()
- throws if empty/not found, does not throw if duplicateFirstOrDefault()
- returns default if empty/not found, does not throw if duplicateSingle()
- throws if empty/not found, throws if duplicate existsSingleOrDefault()
- returns default if empty/not found, throws if duplicate existsYou change default value in MySQL configuration file (option connect_timeout in mysqld section) -
[mysqld]
connect_timeout=100
If this file is not accessible for you, then you can set this value using this statement -
SET GLOBAL connect_timeout=100;
You can simply use:
ps -o args= -f -p ProcessPid
It looks like you probably pasted this (or used a word processor like MS Word) using a kind of double-quotes that are not recognized by the browser. Please check that your code uses actual double-quotes like this one "
, which is different from the following character: ”
Replace the meta tag with this one and try again:
<meta http-equiv="refresh" content="5" >
Try this
<head>
<style type ="text/css" >
.footer{
position: fixed;
text-align: center;
bottom: 0px;
width: 100%;
}
</style>
</head>
<body>
<div class="footer">All Rights Reserved</div>
</body>
Your Fragment can subclass ListFragment.
And onCreateView() from ListFragment
will return a ListView
you can then populate.
Just include this script
http://code.jquery.com/jquery-migrate-1.0.0.js
after you include your jquery javascript file.
So I did mine with the full styling and border colors like this:
new OutlineButton(
shape: StadiumBorder(),
textColor: Colors.blue,
child: Text('Button Text'),
borderSide: BorderSide(
color: Colors.blue, style: BorderStyle.solid,
width: 1),
onPressed: () {},
)
We can append or prepend two lists or list&array
Append:
var l = List(1,2,3)
l = l :+ 4
Result : 1 2 3 4
var ar = Array(4, 5, 6)
for(x <- ar)
{ l = l :+ x }
l.foreach(println)
Result:1 2 3 4 5 6
Prepending:
var l = List[Int]()
for(x <- ar)
{ l= x :: l } //prepending
l.foreach(println)
Result:6 5 4 1 2 3
Several ways to create an Empty Observable:
They just differ on how you are going to use it further (what events it will emit after: next
, complete
or do nothing
) e.g.:
Observable.never()
- emits no events and never ends.Observable.empty()
- emits only complete
.Observable.of({})
- emits both next
and complete
(Empty object literal passed as an example).Use it on your exact needs)
Similar to getting the length of a dataframe, len(df)
, the following worked for pandas and blaze:
Total = sum(df['MyColumn'])
or alternatively
Total = sum(df.MyColumn)
print Total
The smart way to fix that problem is to compile using the latest SDK and use the cross compilation options when compiling. To use the options completely correctly requires the rt.jar
of a JRE (not JDK) of the target version.
Given the nature of that applet, it looks like it could be compiled for use with Java 1.1.
Try purge
sudo aptitude purge phpmyadmin
Not sure this works with plain old apt-get
though
A primitive quick fix that works.
If you only use OpenFileDialog
, you can capture the FileName
, SafeFileName
, then subtract to get folder path:
exampleFileName = ofd.SafeFileName;
exampleFileNameFull = ofd.FileName;
exampleFileNameFolder = ofd.FileNameFull.Replace(ofd.FileName, "");
Sorry, the short answer is no. CSS (2.1) will only mark up the elements of a DOM, not their attributes. You'd have to apply a specific class to each input.
Bummer I know, because that would be incredibly useful.
I know you've said you'd prefer CSS over JavaScript, but you should still consider using jQuery. It provides a very clean and elegant way of adding styles to DOM elements based on attributes.
where 0 is initial value
Array.reduce((currentValue, value) => currentValue +value,0)
or
Array.reduce((currentValue, value) =>{ return currentValue +value},0)
or
[1,3,4].reduce(function(currentValue, value) { return currentValue + value},0)
Here is another way using list comprehension (some people might find it debatable). It is very approachable for simple tests, e.g. comparisons on object attributes (which I need a lot):
el = [x for x in mylist if x.attr == "foo"][0]
Of course this assumes the existence (and, actually, uniqueness) of a suitable element in the list.
It's the first result on Google: http://docs.python.org/library/stdtypes.html#string-formatting
See also the new format() function: http://docs.python.org/library/stdtypes.html#str.format
Go to terminal
$ adb -s UDID shell
$ ip addr | grep inet
or
$ netcfg | grep inet
private void button1_Click(object sender, EventArgs e)
{
String query = "INSERT INTO product (productid, productname,productdesc,productqty) VALUES (@txtitemid,@txtitemname,@txtitemdesc,@txtitemqty)";
try
{
using (SqlCommand command = new SqlCommand(query, con))
{
command.Parameters.AddWithValue("@txtitemid", txtitemid.Text);
command.Parameters.AddWithValue("@txtitemname", txtitemname.Text);
command.Parameters.AddWithValue("@txtitemdesc", txtitemdesc.Text);
command.Parameters.AddWithValue("@txtitemqty", txtitemqty.Text);
con.Open();
int result = command.ExecuteNonQuery();
// Check Error
if (result < 0)
MessageBox.Show("Error");
MessageBox.Show("Record...!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.Close();
loader();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
This is simple and sort. Use hsla css function like below
.transparent {
background-color: hsla(0,0%,4%,.4);
}
Either return;
from the method early, or throw
an exception.
There is no other way to prevent further code from being executed short of exiting the process completely.
An alternative is to normalize the data. Below are three sets of data with widely varying ranges. In the top chart you can see the variation in one series clearly, in another not so clearly, and the third not at all.
In the second range, I have adjusted the series names to include the data range, using this formula in cell C15 and copying it to D15:E15
=C2&" ("&MIN(C3:C9)&" to "&MAX(C3:C9)&")"
I have normalized the values in the data range using this formula in C15 and copying it to the entire range C16:E22
=100*(C3-MIN(C$3:C$9))/(MAX(C$3:C$9)-MIN(C$3:C$9))
In the second chart, you can see a pattern: all series have a low in January, rising to a high in March, and dropping to medium-low value in June or July.
You can modify the normalizing formula however you need:
=100*C3/MAX(C$3:C$9)
=C3/MAX(C$3:C$9)
=(C3-AVERAGE(C$3:C$9))/STDEV(C$3:C$9)
etc.
top5 = array[:5]
array[start:stop:step]
array[start:]
, array[:stop]
, array[::step]
import itertools
top5 = itertools.islice(my_list, 5) # grab the first five elements
You can't slice a generator directly in Python. itertools.islice()
will wrap an object in a new slicing generator using the syntax itertools.islice(generator, start, stop, step)
Remember, slicing a generator will exhaust it partially. If you want to keep the entire generator intact, perhaps turn it into a tuple or list first, like: result = tuple(generator)
Upgrading NPM to the latest version can greatly help with this. dule's answer above is right to say that dependency management is a bit broken, but it seems that this is mainly for older versions of npm.
The command npm list
gives you a list of all installed node_modules
. When I upgraded from version 1.4.2 to version 2.7.4, many modules that were previously flagged with WARN unmet dependency
were no longer noted as such.
To update npm, you should type npm install -g npm
on MacOSX or Linux. On Windows, I found that re-downloading and re-running the nodejs installer was a more effective way to update npm.
You can add it:
var meta = document.createElement('meta');
meta.httpEquiv = "X-UA-Compatible";
meta.content = "IE=edge";
document.getElementsByTagName('head')[0].appendChild(meta);
...but I wouldn't be surprised if by the time that ran, the browser had already made its decisions about how to render the page.
The real answer here has to be to output the correct tag from the server in the first place. (Sadly, you can't just not have the tag if you need to support IE. :-| )
Even though you define android:onClick = "DoIt" in XML, you need to make sure your activity (or view context) has public method defined with exact same name and View as parameter. Android wires your definitions with this implementation in activity. At the end, implementation will have same code which you wrote in anonymous inner class. So, in simple words instead of having inner class and listener attachement in activity, you will simply have a public method with implementation code.
I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=D:\test.xls " & _
";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
For i = 0 To rs.Fields.Count - 1
Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
strNaam = rs.Fields(0).Value
Next
rs.MoveNext
Loop
rs.Close
There are other ways, depending on what you want to do, such as GetString (GetString Method Description).
You are mixing mysql and mysqli
Change these lines:
$sql = mysql_query("SELECT * FROM login WHERE username = '".$_POST['username']."' and password = '".md5($_POST['password'])."'");
$row = mysql_num_rows($sql);
to
$sql = mysqli_query($success, "SELECT * FROM login WHERE username = '".$_POST['username']."' and password = '".md5($_POST['password'])."'");
$row = mysqli_num_rows($sql);
If you use all of the months in your code, your IDE won't let you compile, so I think you don't need unit testing.
But if you are using them with reflection, even if you delete one month, it will compile, so it's valid to put a unit test.
In my case I was performing git push heroku master
when I am not on the master branch.
I had to go to master branch first, merge the code with my other branch and then git pushed.
It's pow or powf in <math.h>
There is no special infix operator like in Visual Basic or Python
There are certain circumstances in which even fatal errors should be caught (you might need to do some clean up before exiting gracefully and don’t just die..).
I have implemented a pre_system hook in my CodeIgniter applications so that I can get my fatal errors through emails, and this helped me finding bugs that were not reported (or were reported after they were fixed, as I already knew about them :)).
Sendemail checks if the error has already been reported so that it does not spam you with known errors multiple times.
class PHPFatalError {
public function setHandler() {
register_shutdown_function('handleShutdown');
}
}
function handleShutdown() {
if (($error = error_get_last())) {
ob_start();
echo "<pre>";
var_dump($error);
echo "</pre>";
$message = ob_get_clean();
sendEmail($message);
ob_start();
echo '{"status":"error","message":"Internal application error!"}';
ob_flush();
exit();
}
}
i was looking for the same. and found this solution.
Use negative regex assertion:
location ~ ^/(?!(favicon\.ico|resources|robots\.txt)) {
.... # your stuff
}
Source Negated Regular Expressions in location
Explanation of Regex :
If URL does not match any of the following path
example.com/favicon.ico
example.com/resources
example.com/robots.txt
Then it will go inside that location block and will process it.
This evaluates to true if it already exists:
$("#yourSelect option[value='yourValue']").length > 0;
One PHP-ish (5.2+) & no-Flash way that worked nicely for me:
First, see this post explaining how to get "uploadprogress" extension up and running.
Then, in the page containing the form that you are uploading file(s) from, create the following iframe:
<iframe id="progress_iframe" src="" style="display:none;" scrolling="no" frameborder="0"></iframe>
Next, add this code to your "Submit" button:
onclick="function set() { f=document.getElementById('progress_iframe'); f.style.display='block'; f.src='uploadprogress.php?id=<?=$upload_id?>';} setTimeout(set);"
Now you have a hidden iframe in your form that will come visible and show contents of uploadprogress.php when you click "Submit" to start uploading files. $upload_id must be the same that you are using as the value of hidden field "UPLOAD_IDENTIFIER" in your form.
The uploadprogress.php itself looks about like this (fix and adjust to your needs):
<html>
<head>
<META HTTP-EQUIV='REFRESH' CONTENT='1;URL=?id=<?=$_GET['id']?>'>
</head>
<body>
Upload progress:<br />
<?php
if(!$_GET['id']) die;
$info = uploadprogress_get_info($_GET['id']);
$kbytes_total = round($info['bytes_total'] / 1024);
$kbytes_uploaded = round($info['bytes_uploaded'] / 1024);
echo $kbytes_uploaded.'/'.$kbytes_total.' KB';
?>
</body>
</html>
Note that is self-refreshes every second. You can surely add some nice visual progress bar here (like 2 nested <div>s with different colors) if you like. The iframe with upload progress naturally only works while the upload is in progress, and ends its visible life once the form is submitted and browser reloads to the next page.
The ISO file that suggested in the accepted answer is still not complete. The very complete offline installer is about 24GB! There is only one way to get it. follow these steps:
temp
folderC:\VS Community\
C:\VS
Community\
with this argument: /Layout .
Good Luck
Just go to php.ini then find short_open_tag= Off
set to short_open_tag= On
float percent = (n / (v * 1.0f)) *100
This should do exactly what the author wanted:
<StackPanel Orientation="Horizontal">
<Separator Style="{StaticResource {x:Static ToolBar.SeparatorStyleKey}}" />
</StackPanel>
if you want a horizontal separator, change the Orientation
of the StackPanel
to Vertical
.
I had the same issue and tried almost everything then found after I came to know I was trying it in the wrong block. I was trying it in steps block whereas it needs to be in the environment block.
stage('Release') {
environment {
my_var = sh(script: "/bin/bash ${assign_version} || ls ", , returnStdout: true).trim()
}
steps {
println my_var
}
}
you can convert it into date format by-
new_date<- as.Date(old_date, "%m/%d/%Y")}
from new_date
, you can get the month by strftime()
month<- strftime(new_date, "%m")
old_date<- "01/01/1979"
new_date<- as.Date(old_date, "%m/%d/%Y")
new_date
#[1] "1979-01-01"
month<- strftime(new_date,"%m")
month
#[1] "01"
year<- strftime(new_date, "%Y")
year
#[1] "1979"
Things seem to have changed since Angular 2.0.0
import { Observable } from 'rxjs/Observable';
import { Subscriber } from 'rxjs/Subscriber';
// ...
public fetchModel(uuid: string = undefined): Observable<string> {
if(!uuid) {
return new Observable<TestModel>((subscriber: Subscriber<TestModel>) => subscriber.next(new TestModel())).map(o => JSON.stringify(o));
}
else {
return this.http.get("http://localhost:8080/myapp/api/model/" + uuid)
.map(res => res.text());
}
}
The .next()
function will be called on your subscriber.
- (void)viewDidLoad
{
[self.tableView setSeparatorColor:[UIColor myColor]];
}
I hope that helps - you'll need the self.
to access it, remember.
Swift 4.2
tableView.separatorColor = UIColor.red
This worked for me:
Created __init__.py
file inside parent folder (in your case, inside site-packages
folder). And imported like this:
from site-packages.toolkit.interface import interface
Hope it will be useful for you as well !
I think Todd is correct, but I think there's one other thing you should consider. You can reliably get the home directory from the JVM at runtime, and then you can create files objects relative to that location. It's not that much more trouble, and it's something you'll appreciate if you ever move to another computer or operating system.
File homedir = new File(System.getProperty("user.home"));
File fileToRead = new File(homedir, "java/ex.txt");
In a few words:
it's very simple. this is work for me.
export MYSQL_PWD=password; mysql --user=username -e "statement"
MYSQL_PWD
is one of environment variables from mysql. it's default password when connecting to mysqld.
An alternative solution would be to use some sort of regex
:
for example:
String s = "apple car 04:48 05:18 05:46 06:16 06:46 07:16 07:46 16:46 17:16 17:46 18:16 18:46 19:16";
String results= s.replaceAll("[0-9]", "").replaceAll(" :", ""); //first removing all the numbers then remove space followed by :
System.out.println(results); // output 9
System.out.println(results.length());// output "apple car"
yourValue.ToString("0.00") will work.
Note that if you care about speed and do not need to worry about singularities, solve()
should be preferred to ginv()
because it is much faster, as you can check:
require(MASS)
mat <- matrix(rnorm(1e6),nrow=1e3,ncol=1e3)
t0 <- proc.time()
inv0 <- ginv(mat)
proc.time() - t0
t1 <- proc.time()
inv1 <- solve(mat)
proc.time() - t1
This simple filtering can be achieved in many ways with Python. The best approach is to use "list comprehensions" as follows:
>>> lst = ['a', 'ab', 'abc', 'bac']
>>> [k for k in lst if 'ab' in k]
['ab', 'abc']
Another way is to use the filter
function. In Python 2:
>>> filter(lambda k: 'ab' in k, lst)
['ab', 'abc']
In Python 3, it returns an iterator instead of a list, but you can cast it:
>>> list(filter(lambda k: 'ab' in k, lst))
['ab', 'abc']
Though it's better practice to use a comprehension.
Executing seq(1, 10, 1)
does what 1:10
does. You can change the last parameter of seq
, i.e. by
, to be the step of whatever size you like.
> #a vector of even numbers
> seq(0, 10, by=2) # Explicitly specifying "by" only to increase readability
> [1] 0 2 4 6 8 10
Installing opencv is not that direct. You need to pre-install some packages first.
I would not recommend the unofficial package opencv-python. Does not work properly in macos and ubuntu (see this post). No idea about windows.
There are many webs explaining how to install opencv and all required packages. For example this one.
The problem of trying to install opencv several times is that you need to uninstall completely before attempting again, or you might end having many errors.
Just use:
<TextBlock Text="{Binding Date, StringFormat=\{0:d\}}" />
Two utilities in package taRifx can be used in concert to produce multi-row tables of nested heirarchies.
library(datasets)
library(taRifx)
library(xtable)
test.by <- bytable(ChickWeight$weight, list( ChickWeight$Chick, ChickWeight$Diet) )
colnames(test.by) <- c('Diet','Chick','Mean Weight')
print(latex.table.by(test.by), include.rownames = FALSE, include.colnames = TRUE, sanitize.text.function = force)
# then add \usepackage{multirow} to the preamble of your LaTeX document
# for longtable support, add ,tabular.environment='longtable' to the print command (plus add in ,floating=FALSE), then \usepackage{longtable} to the LaTeX preamble
I am using php 7.3.8 on a manjaro and I was working with Persian content. This solved my problem:
$html = 'hi</b><p>????<div>?????9 ?';
$doc = new DOMDocument('1.0', 'UTF-8');
$doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
print $doc->saveHTML($doc->documentElement) . PHP_EOL . PHP_EOL;
I have experienced this same problem under CentOS 7
In may case, the problem went off after installation of libcurl-devel
(libcurl
was already installed on this machine)
In Linq-to-SQL if you try to get the first element on a query with no results you will get sequence contains no elements
error. I can assure you that the mentioned error is not equal to object reference not set to an instance of an object
.
in conclusion no, it won't return null since null can't say sequence contains no elements
it will always say object reference not set to an instance of an object
;)
You can use fuckit module.
Wrap your code in a function with @fuckit
decorator:
@fuckit
def func():
code a
code b #if b fails, it should ignore, and go to c.
code c #if c fails, go to d
code d
Nop, you have a connection error, please check your IP server adress or your firewall.
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: "Connection refused: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
I found this method working quite well (for me) to produce a flat array of unique values:
$uniqueNames = User::select('name')->distinct()->pluck('name')->toArray();
If you ran ->toSql()
on this query builder, you will see it generates a query like this:
select distinct `name` from `users`
The ->pluck()
is handled by illuminate\collection lib (not via sql query).
I faced the same problem and I solved it doing the following:
Go to /home/[USER]/Android/Sdk/tools and execute:
$android list sdk -a
Which will show a list like:
... and many more
Then, execute the command (attention! at your computer the third option may be different):
$android update sdk -a -u -t 3
It will install the 23.0.1 SDK Platform-tools components.
Try to build your project again.
I think this question is a bit misleading since, toString() in Java isn't just a way to cast something to a String. That is what casting via (string) or String.valueOf() does, and it works as well in PHP.
// Java
String myText = (string) myVar;
// PHP
$myText = (string) $myVar;
Note that this can be problematic as Java is type-safe (see here for more details).
But as I said, this is casting and therefore not the equivalent of Java's toString().
toString in Java doesn't just cast an object to a String. It instead will give you the String representation. And that's what __toString() in PHP does.
// Java
class SomeClass{
public String toString(){
return "some string representation";
}
}
// PHP
class SomeClass{
public function __toString()
{
return "some string representation";
}
}
And from the other side:
// Java
new SomeClass().toString(); // "Some string representation"
// PHP
strval(new SomeClass); // "Some string representation"
What do I mean by "giving the String representation"? Imagine a class for a library with millions of books.
These are both valid approaches but with very different goals, neither is a perfect solution for every case and you have to chose wisely which fits better for your needs.
Sure, there are even more options:
$no = 421337 // A number in PHP
$str = "$no"; // In PHP, stuff inside "" is calculated and variables are replaced
$str = print_r($no, true); // Same as String.format();
$str = settype($no, 'string'); // Sets $no to the String Type
$str = strval($no); // Get the string value of $no
$str = $no . ''; // As you said concatenate an empty string works too
All of these methods will return a String, some of them using __toString internally and some others will fail on Objects. Take a look at the PHP documentation for more details.
I have made a workaround to solve this problem. Visit the below link for more details http://code-outofbox.blogspot.com/2015/07/java-prepared-statement-print-values.html
Solution:
// Initialize connection
PreparedStatement prepStmt = connection.prepareStatement(sql);
PreparedStatementHelper prepHelper = new PreparedStatementHelper(prepStmt);
// User prepHelper.setXXX(indx++, value);
// .....
try {
Pattern pattern = Pattern.compile("\\?");
Matcher matcher = pattern.matcher(sql);
StringBuffer sb = new StringBuffer();
int indx = 1; // Parameter begin with index 1
while (matcher.find()) {
matcher.appendReplacement(sb, prepHelper.getParameter(indx++));
}
matcher.appendTail(sb);
LOGGER.debug("Executing Query [" + sb.toString() + "] with Database[" + /*db name*/ + "] ...");
} catch (Exception ex) {
LOGGER.debug("Executing Query [" + sql + "] with Database[" + /*db name*/+ "] ...");
}
/****************************************************/
package java.sql;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.Date;
import java.sql.NClob;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.Ref;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
public class PreparedStatementHelper implements PreparedStatement {
private PreparedStatement prepStmt;
private String[] values;
public PreparedStatementHelper(PreparedStatement prepStmt) throws SQLException {
this.prepStmt = prepStmt;
this.values = new String[this.prepStmt.getParameterMetaData().getParameterCount()];
}
public String getParameter(int index) {
String value = this.values[index-1];
return String.valueOf(value);
}
private void setParameter(int index, Object value) {
String valueStr = "";
if (value instanceof String) {
valueStr = "'" + String.valueOf(value).replaceAll("'", "''") + "'";
} else if (value instanceof Integer) {
valueStr = String.valueOf(value);
} else if (value instanceof Date || value instanceof Time || value instanceof Timestamp) {
valueStr = "'" + String.valueOf(value) + "'";
} else {
valueStr = String.valueOf(value);
}
this.values[index-1] = valueStr;
}
@Override
public ResultSet executeQuery(String sql) throws SQLException {
return this.prepStmt.executeQuery(sql);
}
@Override
public int executeUpdate(String sql) throws SQLException {
return this.prepStmt.executeUpdate(sql);
}
@Override
public void close() throws SQLException {
this.prepStmt.close();
}
@Override
public int getMaxFieldSize() throws SQLException {
return this.prepStmt.getMaxFieldSize();
}
@Override
public void setMaxFieldSize(int max) throws SQLException {
this.prepStmt.setMaxFieldSize(max);
}
@Override
public int getMaxRows() throws SQLException {
return this.prepStmt.getMaxRows();
}
@Override
public void setMaxRows(int max) throws SQLException {
this.prepStmt.setMaxRows(max);
}
@Override
public void setEscapeProcessing(boolean enable) throws SQLException {
this.prepStmt.setEscapeProcessing(enable);
}
@Override
public int getQueryTimeout() throws SQLException {
return this.prepStmt.getQueryTimeout();
}
@Override
public void setQueryTimeout(int seconds) throws SQLException {
this.prepStmt.setQueryTimeout(seconds);
}
@Override
public void cancel() throws SQLException {
this.prepStmt.cancel();
}
@Override
public SQLWarning getWarnings() throws SQLException {
return this.prepStmt.getWarnings();
}
@Override
public void clearWarnings() throws SQLException {
this.prepStmt.clearWarnings();
}
@Override
public void setCursorName(String name) throws SQLException {
this.prepStmt.setCursorName(name);
}
@Override
public boolean execute(String sql) throws SQLException {
return this.prepStmt.execute(sql);
}
@Override
public ResultSet getResultSet() throws SQLException {
return this.prepStmt.getResultSet();
}
@Override
public int getUpdateCount() throws SQLException {
return this.prepStmt.getUpdateCount();
}
@Override
public boolean getMoreResults() throws SQLException {
return this.prepStmt.getMoreResults();
}
@Override
public void setFetchDirection(int direction) throws SQLException {
this.prepStmt.setFetchDirection(direction);
}
@Override
public int getFetchDirection() throws SQLException {
return this.prepStmt.getFetchDirection();
}
@Override
public void setFetchSize(int rows) throws SQLException {
this.prepStmt.setFetchSize(rows);
}
@Override
public int getFetchSize() throws SQLException {
return this.prepStmt.getFetchSize();
}
@Override
public int getResultSetConcurrency() throws SQLException {
return this.prepStmt.getResultSetConcurrency();
}
@Override
public int getResultSetType() throws SQLException {
return this.prepStmt.getResultSetType();
}
@Override
public void addBatch(String sql) throws SQLException {
this.prepStmt.addBatch(sql);
}
@Override
public void clearBatch() throws SQLException {
this.prepStmt.clearBatch();
}
@Override
public int[] executeBatch() throws SQLException {
return this.prepStmt.executeBatch();
}
@Override
public Connection getConnection() throws SQLException {
return this.prepStmt.getConnection();
}
@Override
public boolean getMoreResults(int current) throws SQLException {
return this.prepStmt.getMoreResults(current);
}
@Override
public ResultSet getGeneratedKeys() throws SQLException {
return this.prepStmt.getGeneratedKeys();
}
@Override
public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
return this.prepStmt.executeUpdate(sql, autoGeneratedKeys);
}
@Override
public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
return this.prepStmt.executeUpdate(sql, columnIndexes);
}
@Override
public int executeUpdate(String sql, String[] columnNames) throws SQLException {
return this.prepStmt.executeUpdate(sql, columnNames);
}
@Override
public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
return this.prepStmt.execute(sql, autoGeneratedKeys);
}
@Override
public boolean execute(String sql, int[] columnIndexes) throws SQLException {
return this.prepStmt.execute(sql, columnIndexes);
}
@Override
public boolean execute(String sql, String[] columnNames) throws SQLException {
return this.prepStmt.execute(sql, columnNames);
}
@Override
public int getResultSetHoldability() throws SQLException {
return this.prepStmt.getResultSetHoldability();
}
@Override
public boolean isClosed() throws SQLException {
return this.prepStmt.isClosed();
}
@Override
public void setPoolable(boolean poolable) throws SQLException {
this.prepStmt.setPoolable(poolable);
}
@Override
public boolean isPoolable() throws SQLException {
return this.prepStmt.isPoolable();
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return this.prepStmt.unwrap(iface);
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return this.prepStmt.isWrapperFor(iface);
}
@Override
public ResultSet executeQuery() throws SQLException {
return this.prepStmt.executeQuery();
}
@Override
public int executeUpdate() throws SQLException {
return this.prepStmt.executeUpdate();
}
@Override
public void setNull(int parameterIndex, int sqlType) throws SQLException {
this.prepStmt.setNull(parameterIndex, sqlType);
setParameter(parameterIndex, null);
}
@Override
public void setBoolean(int parameterIndex, boolean x) throws SQLException {
this.prepStmt.setBoolean(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setByte(int parameterIndex, byte x) throws SQLException {
this.prepStmt.setByte(parameterIndex, x);
// TODO Add to tree set
}
@Override
public void setShort(int parameterIndex, short x) throws SQLException {
this.prepStmt.setShort(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setInt(int parameterIndex, int x) throws SQLException {
this.prepStmt.setInt(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setLong(int parameterIndex, long x) throws SQLException {
this.prepStmt.setLong(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setFloat(int parameterIndex, float x) throws SQLException {
this.prepStmt.setFloat(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setDouble(int parameterIndex, double x) throws SQLException {
this.prepStmt.setDouble(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException {
this.prepStmt.setBigDecimal(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setString(int parameterIndex, String x) throws SQLException {
this.prepStmt.setString(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setBytes(int parameterIndex, byte[] x) throws SQLException {
this.prepStmt.setBytes(parameterIndex, x);
// TODO Add to tree set
}
@Override
public void setDate(int parameterIndex, Date x) throws SQLException {
this.prepStmt.setDate(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setTime(int parameterIndex, Time x) throws SQLException {
this.prepStmt.setTime(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException {
this.prepStmt.setTimestamp(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException {
this.prepStmt.setAsciiStream(parameterIndex, x, length);
}
@SuppressWarnings("deprecation")
@Override
public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException {
this.prepStmt.setUnicodeStream(parameterIndex, x, length);
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException {
this.prepStmt.setBinaryStream(parameterIndex, x, length);
}
@Override
public void clearParameters() throws SQLException {
this.prepStmt.clearParameters();
}
@Override
public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException {
this.prepStmt.setObject(parameterIndex, x, targetSqlType);
setParameter(parameterIndex, x);
}
@Override
public void setObject(int parameterIndex, Object x) throws SQLException {
this.prepStmt.setObject(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public boolean execute() throws SQLException {
return this.prepStmt.execute();
}
@Override
public void addBatch() throws SQLException {
this.prepStmt.addBatch();
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException {
this.prepStmt.setCharacterStream(parameterIndex, reader, length);
}
@Override
public void setRef(int parameterIndex, Ref x) throws SQLException {
this.prepStmt.setRef(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setBlob(int parameterIndex, Blob x) throws SQLException {
this.prepStmt.setBlob(parameterIndex, x);
}
@Override
public void setClob(int parameterIndex, Clob x) throws SQLException {
this.prepStmt.setClob(parameterIndex, x);
}
@Override
public void setArray(int parameterIndex, Array x) throws SQLException {
this.prepStmt.setArray(parameterIndex, x);
// TODO Add to tree set
}
@Override
public ResultSetMetaData getMetaData() throws SQLException {
return this.prepStmt.getMetaData();
}
@Override
public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException {
this.prepStmt.setDate(parameterIndex, x, cal);
setParameter(parameterIndex, x);
}
@Override
public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException {
this.prepStmt.setTime(parameterIndex, x, cal);
setParameter(parameterIndex, x);
}
@Override
public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException {
this.prepStmt.setTimestamp(parameterIndex, x, cal);
setParameter(parameterIndex, x);
}
@Override
public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException {
this.prepStmt.setNull(parameterIndex, sqlType, typeName);
setParameter(parameterIndex, null);
}
@Override
public void setURL(int parameterIndex, URL x) throws SQLException {
this.prepStmt.setURL(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public ParameterMetaData getParameterMetaData() throws SQLException {
return this.prepStmt.getParameterMetaData();
}
@Override
public void setRowId(int parameterIndex, RowId x) throws SQLException {
this.prepStmt.setRowId(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setNString(int parameterIndex, String value) throws SQLException {
this.prepStmt.setNString(parameterIndex, value);
setParameter(parameterIndex, value);
}
@Override
public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException {
this.prepStmt.setNCharacterStream(parameterIndex, value, length);
}
@Override
public void setNClob(int parameterIndex, NClob value) throws SQLException {
this.prepStmt.setNClob(parameterIndex, value);
}
@Override
public void setClob(int parameterIndex, Reader reader, long length) throws SQLException {
this.prepStmt.setClob(parameterIndex, reader, length);
}
@Override
public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException {
this.prepStmt.setBlob(parameterIndex, inputStream, length);
}
@Override
public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException {
this.prepStmt.setNClob(parameterIndex, reader, length);
}
@Override
public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException {
this.prepStmt.setSQLXML(parameterIndex, xmlObject);
setParameter(parameterIndex, xmlObject);
}
@Override
public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException {
this.prepStmt.setObject(parameterIndex, x, targetSqlType, scaleOrLength);
setParameter(parameterIndex, x);
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException {
this.prepStmt.setAsciiStream(parameterIndex, x, length);
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException {
this.prepStmt.setBinaryStream(parameterIndex, x, length);
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException {
this.prepStmt.setCharacterStream(parameterIndex, reader, length);
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException {
this.prepStmt.setAsciiStream(parameterIndex, x);
// TODO Add to tree set
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException {
this.prepStmt.setBinaryStream(parameterIndex, x);
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException {
this.prepStmt.setCharacterStream(parameterIndex, reader);
}
@Override
public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException {
this.prepStmt.setNCharacterStream(parameterIndex, value);
}
@Override
public void setClob(int parameterIndex, Reader reader) throws SQLException {
this.prepStmt.setClob(parameterIndex, reader);
// TODO Add to tree set
}
@Override
public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException {
this.prepStmt.setBlob(parameterIndex, inputStream);
}
@Override
public void setNClob(int parameterIndex, Reader reader) throws SQLException {
this.prepStmt.setNClob(parameterIndex, reader);
}
}
Figured it out. Used this instead.
$('.div_class').load('http://en.wikipedia.org/wiki/Cross-origin_resource_sharing #toctitle');
None of the above solutions handled deep nested params with just jQuery, so here is my two cents solution.
If you're using jQuery and you need to handle deep nested parameters, you can use this function below:
/**
* Original code found here: https://github.com/mgalante/jquery.redirect/blob/master/jquery.redirect.js
* I just simplified it for my own taste.
*/
function postForm(parameters, url) {
// generally we post the form with a blank action attribute
if ('undefined' === typeof url) {
url = '';
}
//----------------------------------------
// SOME HELPER FUNCTIONS
//----------------------------------------
var getForm = function (url, values) {
values = removeNulls(values);
var form = $('<form>')
.attr("method", 'POST')
.attr("action", url);
iterateValues(values, [], form, null);
return form;
};
var removeNulls = function (values) {
var propNames = Object.getOwnPropertyNames(values);
for (var i = 0; i < propNames.length; i++) {
var propName = propNames[i];
if (values[propName] === null || values[propName] === undefined) {
delete values[propName];
} else if (typeof values[propName] === 'object') {
values[propName] = removeNulls(values[propName]);
} else if (values[propName].length < 1) {
delete values[propName];
}
}
return values;
};
var iterateValues = function (values, parent, form, isArray) {
var i, iterateParent = [];
Object.keys(values).forEach(function (i) {
if (typeof values[i] === "object") {
iterateParent = parent.slice();
iterateParent.push(i);
iterateValues(values[i], iterateParent, form, Array.isArray(values[i]));
} else {
form.append(getInput(i, values[i], parent, isArray));
}
});
};
var getInput = function (name, value, parent, array) {
var parentString;
if (parent.length > 0) {
parentString = parent[0];
var i;
for (i = 1; i < parent.length; i += 1) {
parentString += "[" + parent[i] + "]";
}
if (array) {
name = parentString + "[" + name + "]";
} else {
name = parentString + "[" + name + "]";
}
}
return $("<input>").attr("type", "hidden")
.attr("name", name)
.attr("value", value);
};
//----------------------------------------
// NOW THE SYNOPSIS
//----------------------------------------
var generatedForm = getForm(url, parameters);
$('body').append(generatedForm);
generatedForm.submit();
generatedForm.remove();
}
Here is an example of how to use it. The html code:
<button id="testButton">Button</button>
<script>
$(document).ready(function () {
$("#testButton").click(function () {
postForm({
csrf_token: "abcd",
rows: [
{
user_id: 1,
permission_group_id: 1
},
{
user_id: 1,
permission_group_id: 2
}
],
object: {
apple: {
color: "red",
age: "23 days",
types: [
"golden",
"opal",
]
}
},
the_null: null, // this will be dropped, like non-checked checkboxes are dropped
});
});
});
</script>
And if you click the test button, it will post the form and you will get the following values in POST:
array(3) {
["csrf_token"] => string(4) "abcd"
["rows"] => array(2) {
[0] => array(2) {
["user_id"] => string(1) "1"
["permission_group_id"] => string(1) "1"
}
[1] => array(2) {
["user_id"] => string(1) "1"
["permission_group_id"] => string(1) "2"
}
}
["object"] => array(1) {
["apple"] => array(3) {
["color"] => string(3) "red"
["age"] => string(7) "23 days"
["types"] => array(2) {
[0] => string(6) "golden"
[1] => string(4) "opal"
}
}
}
}
Note: if you want to post the form to another url than the current page, you can specify the url as the second argument of the postForm function.
So for instance (to re-use your example):
postForm({'q':'a'}, 'http://example.com/');
Hope this helps.
Note2: the code was taken from the redirect plugin. I basically just simplified it for my needs.
I think you are missing the "single page app" meaning.
That doesn't mean you will physically have one .html, instead you will have one main index.html
and several NESTED .html file. So why single page app? Because this way you do not load pages the standard way (i.e. browser call that completely refreshes the full page) but you just load the content part using Angular/Ajax. Since you do not see the flickering between page changes, you have the impression that you didn't move from the page. Thus, you feel like you are staying on a single page.
Now, I'm assuming that you want to have MULTIPLE contents for your SINGLE PAGE app: (e.g.) home, contacts, portfolio and store. Your single page/multiple content app (the angular way) will be organized this way:
index.html
: contains header, <ng-view>
and footer contacts.html
:contains the contact form (no header, no footer)portfolio.html
:contains the portfolio data (no header no footer)store.html
: contains the store, no header no footer.You are in index, you click on the menu called "contacts" and what happens? Angular replaces the <ng-view>
tag with the contacts.html
code
How do you achieve that? with ngRoute
, as you are doing, you will have something like:
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: "templates/index.html",
controller:'MainCtrl',
})
.when('/contacts', {
templateUrl: "templates/contacts.html",
controller:'ContactsCtrl',
})
.otherwise({
template: 'does not exists'
});
});
This will call the right html passing the right controller to it (please note: do not specify ng-controller
directive in contacts.html
if you are using routes)
Then, of course, you can declare as many ng-controller directives inside your contacts.html page. Those will be child controllers of ContactCtrl
(thus inheriting from it). But for a single route, inside the routeProvider
, you can declare a single Controller that will act as the "Father controller of the partial view".
EDIT Imagine the following templates/contacts.html
<div>
<h3>Contacts</h3>
<p>This is contacts page...</p>
</div>
the above routeProvider
will inject a controller into your containing div. Basically the above html automaticaly becomes:
<div ng-controller="ContactsCtrl">
<h3>Contacts</h3>
<p>This is contacts page...</p>
</div>
When I say you can have others controllers, means that you can plug controllers to inner DOM elements, as the following:
<div>
<h3>Contacts</h3>
<p ng-controller="anotherCtrl">Hello {{name}}! This is contacts page...
</p>
</div>
I hope this clarify things a bit.
A
This works for me:
C:\xampp\phpMyAdmin\config.inc.php
$cfg['Servers'][$i]['password'] = 'secret';
Edit: Before you got this error it is most likely that from phpmyadmin->Users you have added password for the root user. In my case that was "secret" so the above primer works for me BUT for you will work this:
$cfg['Servers'][$i]['password'] = 'Enter the password for root you have added before you got this error';
From the manual:
If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling).
The prepare statement likely caused an error because the db would be unable to prepare the statement. Try testing for an error immediately after you prepare your query and before you execute it.
$qry = '
INSERT INTO non-existant-table (id, score)
SELECT id, 40
FROM another-non-existant-table
WHERE description LIKE "%:search_string%"
AND available = "yes"
ON DUPLICATE KEY UPDATE score = score + 40
';
$sth = $this->pdo->prepare($qry);
print_r($this->pdo->errorInfo());
The '
character in SQL is used for string constants. In this case it is used for ending the string constant and not for comment.
I tried all of the previous answers and nothing helped my case with my clients!
Then my client remembered he had the Facebook App installed on his device. After he removed it. the login worked perfectly.
The hashkey had been changed, and I've replaced the old hash keys at Facebook Developers Console with the key from the error (as suggested above), and it works!
The Facebook App itself might be the issue, so you better figure this out on a device with the Facebook app installed and on a device with the Facebook app not installed and handle both cases...
SELECT table_name
FROM information_schema.tables
WHERE table_type='BASE TABLE'
AND table_schema='public';
For MySQL you would need table_schema='dbName' and for MSSQL remove that condition.
Notice that "only those tables and views are shown that the current user has access to". Also, if you have access to many databases and want to limit the result to a certain database, you can achieve that by adding condition AND table_catalog='yourDatabase' (in PostgreSQL).
If you'd also like to get rid of the header showing row names and footer showing row count, you could either start the psql with command line option -t (short for --tuples-only) or you can toggle the setting in psql's command line by \t (short for \pset tuples_only). This could be useful for example when piping output to another command with \g [ |command ].
I believe it is -- when you are working with JS strings.
If you are generating HTML, though, you will have to use <br />
tags (not \n
, as you're not dealing with JS anymore)
You may install your coinhsl library in one of your standard libraries directories and run 'ldconfig` before doing your ppyipopt install
I believe the command you are looking for is start /b *command*
For unix, nohup
represents 'no hangup', which is slightly different than a background job (which would be *command* &
. I believe that the above command should be similar to a background job for windows.
The regular expression you are after will most likely be huge and a nightmare to maintain especially for people who are not that familiar with regular expressions.
I think it would be easier to break your regex down and do it one bit at a time. It might take a bit more to do, but I am pretty sure that maintaining it and debugging it would be easier. This would also allow you to provide more directed error messages to your users (other than just Invalid Password
) which should improve user experience.
From what I am seeing you are pretty fluent in regex, so I would presume that giving you the regular expressions to do what you need would be futile.
Seeing your comment, this is how I would go about it:
Must be eight characters Long: You do not need a regex for this. Using the .Length
property should be enough.
Including one uppercase letter: You can use the [A-Z]+
regular expression. If the string contains at least one upper case letter, this regular expression will yield true
.
One special character: You can use either the \W
which will match any character which is not a letter or a number or else, you can use something like so [!@#]
to specify a custom list of special characters. Note though that characters such as $
, ^
, (
and )
are special characters in the regular expression language, so they need to be escaped like so: \$
. So in short, you might use the \W
.
Alphanumeric characters: Using the \w+
should match any letter and number and underscore.
Take a look at this tutorial for more information.
Here is what I discovery since my Mac OS doesn't use all the easy answers. I used the jot command to generate a number since the $RANDOM variable solutions seems not to be very random in my test. When testing my solution I had a wide variance in the solutions provided in the output.
RANDOM1=`jot -r 1 1 235886`
#range of jot ( 1 235886 ) found from earlier wc -w /usr/share/dict/web2
echo $RANDOM1
head -n $RANDOM1 /usr/share/dict/web2 | tail -n 1
The echo of the variable is to get a visual of the generated random number.
This query uses the Group By
and and Having
clauses to allow you to select (locate and list out) for each duplicate record. The As
clause is a convenience to refer to Quantity
in the select
and Order By
clauses, but is not really part of getting you the duplicate rows.
Select
Title,
Count( Title ) As [Quantity]
From
Training
Group By
Title
Having
Count( Title ) > 1
Order By
Quantity desc
bool b = str.Equals("1")? true : false;
Or even better, as suggested in a comment below:
bool b = str.Equals("1");
I prefer TailMe because of the possibility to watch several log files simultaneously in one window: http://www.dschensky.de/Software/Staff/tailme_en.htm
Very Straightforward!
function parseQueryString(){
var assoc = {};
var keyValues = location.search.slice(1).split('&');
var decode = function(s){
return decodeURIComponent(s.replace(/\+/g, ' '));
};
for (var i = 0; i < keyValues.length; ++i) {
var key = keyValues[i].split('=');
if (1 < key.length) {
assoc[decode(key[0])] = decode(key[1]);
}
}
return assoc;
}
Edit 18 Nov 2016
This code also work (for those who prefer another solution , without using ActiveX)
var isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
// true on IE11
// false on Edge and other IEs/browsers.
Original Answer
In order to check Ie11 , you can use this : ( tested)
(or run this)
!(window.ActiveXObject) && "ActiveXObject" in window
I have all VMS of IE :
Notice : this wont work for IE11 :
as you can see here , it returns true :
So what can we do :
Apparently , they added the machine bit space :
ie11 :
"Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; rv:11.0) like Gecko"
ie12 :
"Mozilla/5.0 (Windows NT 6.3; Win64; x64; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; rv:11.0) like Gecko"
so we can do:
/x64|x32/ig.test(window.navigator.userAgent)
this will return true only for ie11.
My answer is similar to this one on ServerFault.com.
If you want to be more conservative than granting "all privileges", you might want to try something more like these.
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO some_user_;
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO some_user_;
The use of public
there refers to the name of the default schema created for every new database/catalog. Replace with your own name if you created a schema.
To access a schema at all, for any action, the user must be granted "usage" rights. Before a user can select, insert, update, or delete, a user must first be granted "usage" to a schema.
You will not notice this requirement when first using Postgres. By default every database has a first schema named public
. And every user by default has been automatically been granted "usage" rights to that particular schema. When adding additional schema, then you must explicitly grant usage rights.
GRANT USAGE ON SCHEMA some_schema_ TO some_user_ ;
Excerpt from the Postgres doc:
For schemas, allows access to objects contained in the specified schema (assuming that the objects' own privilege requirements are also met). Essentially this allows the grantee to "look up" objects within the schema. Without this permission, it is still possible to see the object names, e.g. by querying the system tables. Also, after revoking this permission, existing backends might have statements that have previously performed this lookup, so this is not a completely secure way to prevent object access.
For more discussion see the Question, What GRANT USAGE ON SCHEMA exactly do?. Pay special attention to the Answer by Postgres expert Craig Ringer.
These commands only affect existing objects. Tables and such you create in the future get default privileges until you re-execute those lines above. See the other answer by Erwin Brandstetter to change the defaults thereby affecting future objects.
You can prefer quick-json parser to meet your requirement...
quick-json parser is very straight forward, flexible, very fast and customizable. Try this out
[quick-json parser] (https://code.google.com/p/quick-json/) - quick-json features -
Compliant with JSON specification (RFC4627)
High-Performance JSON parser
Supports Flexible/Configurable parsing approach
Configurable validation of key/value pairs of any JSON Heirarchy
Easy to use # Very Less foot print
Raises developer friendly and easy to trace exceptions
Pluggable Custom Validation support - Keys/Values can be validated by configuring custom validators as and when encountered
Validating and Non-Validating parser support
Support for two types of configuration (JSON/XML) for using quick-json validating parser
Require JDK 1.5 # No dependency on external libraries
Support for Json Generation through object serialization
Support for collection type selection during parsing process
For e.g.
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);
Although it is safe to declare a static ObjectMapper in terms of thread safety, you should be aware that constructing static Object variables in Java is considered bad practice. For more details, see Why are static variables considered evil? (and if you'd like, my answer)
In short, statics should be avoided because the make it difficult to write concise unit tests. For example, with a static final ObjectMapper, you can't swap out the JSON serialization for dummy code or a no-op.
In addition, a static final prevents you from ever reconfiguring ObjectMapper at runtime. You might not envision a reason for that now, but if you lock yourself into a static final pattern, nothing short of tearing down the classloader will let you re-initialize it.
In the case of ObjectMapper its fine, but in general it is bad practice and there is no advantage over using a singleton pattern or inversion-of-control to manage your long-lived objects.
Try using jQuery for the event listener, it will then work in Firefox.
myAudio = new Audio('someSound.ogg');
$(myAudio).bind('ended', function() {
myAudio.currentTime = 0;
myAudio.play();
});
myAudio.play();
Something like that.
You will also get this error if you have a generic declaration for both your class and your method. For example the code shown below gives this compile error.
public class Foo <T> {
T var;
public <T> void doSomething(Class <T> cls) throws InstantiationException, IllegalAccessException {
this.var = cls.newInstance();
}
}
This code does compile (note T removed from method declaration):
public class Foo <T> {
T var;
public void doSomething(Class <T> cls) throws InstantiationException, IllegalAccessException {
this.var = cls.newInstance();
}
}
If you know the white space is only due to spaces, you can use:
$string = str_replace(' ','',$string);
But if it could be due to space, tab...you can use:
$string = preg_replace('/\s+/','',$string);
$('input[name=test]').click(function () {
if (this.id == "watch-me") {
$("#show-me").show('slow');
} else {
$("#show-me").hide('slow');
}
});
You cannot start a container from a Dockerfile.
The process goes like this:
Dockerfile =[
docker build
]=> Docker image =[docker run
]=> Docker container
To start (or run) a container you need an image. To create an image you need to build the Dockerfile[1].
[1]: you can also docker import
an image from a tarball or again docker load
.
its even simpler than that. Using HTML you can just add this metatag to your page (first thing on the page):
<meta http-equiv="X-UA-Compatible" content="IE=7" />
If you wanted to do it using.net, you just have to send your http request with that meta information in the header. This would require a page refresh to work though.
Also, you can look at a similar question here: Compatibility Mode in IE8 using VBScript
In Java, you can use the library class sun.net.util.IPAddressUtil
:
IPAddressUtil.isIPv6LiteralAddress(iPaddress);
Your syntax is incorrect. The var
keyword in your for
loop must be followed by a variable name, in this case its propName
var propValue;
for(var propName in nyc) {
propValue = nyc[propName]
console.log(propName,propValue);
}
I suggest you have a look here for some basics:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
Adding more to Jason's more generalized way of retrieving the POST data or GET data
from flask_restful import reqparse
def parse_arg_from_requests(arg, **kwargs):
parse = reqparse.RequestParser()
parse.add_argument(arg, **kwargs)
args = parse.parse_args()
return args[arg]
form_field_value = parse_arg_from_requests('FormFieldValue')
Cookies are stored in browser as a text file format.It stores limited amount of data, up to 4kb[4096bytes].A single Cookie can not hold multiple values but yes we can have more than one cookie.
Cookies are easily accessible so they are less secure. The setcookie() function must appear BEFORE the tag.
Sessions are stored in server side.There is no such storage limit on session .Sessions can hold multiple variables.Since they are not easily accessible hence are more secure than cookies.
Take a look at the Mockito API docs. As the linked document mentions (Point # 12) you can use any of the doThrow()
,doAnswer()
,doNothing()
,doReturn()
family of methods from Mockito framework to mock void methods.
For example,
Mockito.doThrow(new Exception()).when(instance).methodName();
or if you want to combine it with follow-up behavior,
Mockito.doThrow(new Exception()).doNothing().when(instance).methodName();
Presuming that you are looking at mocking the setter setState(String s)
in the class World below is the code uses doAnswer
method to mock the setState
.
World mockWorld = mock(World.class);
doAnswer(new Answer<Void>() {
public Void answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
System.out.println("called with arguments: " + Arrays.toString(args));
return null;
}
}).when(mockWorld).setState(anyString());
You should probably use the ngHref directive along with the ngClick:
<a ng-href='#here' ng-click='go()' >click me</a>
Here is an example: http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
{{msg}}
<a ng-href='#here' ng-click='go()' >click me</a>
<div style='height:1000px'>
<a id='here'></a>
</div>
<h1>here</h1>
</body>
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.go = function() {
$scope.msg = 'clicked';
}
});
I don't know if this will work with the library you are using but it will at least let you link and use the ngClick function.
** Update **
Here is a demo of the set and get working fine with a service.
http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, sharedProperties) {
$scope.name = 'World';
$scope.go = function(item) {
sharedProperties.setListName(item);
}
$scope.getItem = function() {
$scope.msg = sharedProperties.getListName();
}
});
app.service('sharedProperties', function () {
var list_name = '';
return {
getListName: function() {
return list_name;
},
setListName: function(name) {
list_name = name;
}
};
});
* Edit *
Please review https://github.com/centralway/lungo-angular-bridge which talks about how to use lungo and angular. Also note that if your page is completely reloading when browsing to another link, you will need to persist your shared properties into localstorage and/or a cookie.
Although it is a late answer, I would say this will help you...
$query = $this->db
->select('user_id, count(user_id) AS num_of_time')
->group_by('user_id')
->order_by('num_of_time', 'desc')
->get('tablename', 10);
print_r($query->result());
You can just convert everything to lowercase for the purposes of sorting:
SELECT * FROM NOTES ORDER BY LOWER(title);
If you want to make sure that the uppercase ones still end up ahead of the lowercase ones, just add that as a secondary sort:
SELECT * FROM NOTES ORDER BY LOWER(title), title;
You can use the Range object in VBA to set the value of a named cell, just like any other cell.
Range("C1").Value = Inputbox("Which job number would you like to add to the list?)
Where "C1" is the name of the cell you want to update.
My Excel VBA is a little bit old and crusty, so there may be a better way to do this in newer versions of Excel.
The performance difference between a switch
and if...else if...else
is small, they basically do the same work. One difference between them that may make a difference is that the expression to test is only evaluated once in a switch
while it's evaluated for each if
. If it's costly to evaluate the expression, doing it one time is of course faster than doing it a hundred times.
The difference in implementation of those commands (and all script in general) differs quite a bit between browsers. It's common to see rather big performance differences for the same code in different browsers.
As you can hardly performance test all code in all browsers, you should go for the code that fits best for what you are doing, and try to reduce the amount of work done rather than optimising how it's done.
You are testing if the values of the variables error
and Already
are present in RepoOutput[RepoName.index(repo)]
. If these variables don't exist then an undefined object is used.
Both of your if
and elif
tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].
I think you wanted to test if certain strings are in the value instead:
{% if "error" in RepoOutput[RepoName.index(repo)] %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
<td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>
Other corrections I made:
{% elif ... %}
instead of {$ elif ... %}
.</tr>
tag out of the if
conditional structure, it needs to be there always.id
attributeNote that most likely you want to use a class
attribute instead here, not an id
, the latter must have a value that must be unique across your HTML document.
Personally, I'd set the class value here and reduce the duplication a little:
{% if "Already" in RepoOutput[RepoName.index(repo)] %}
{% set row_class = "good" %}
{% else %}
{% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>
long
can only take string convertibles which can end in a base 10 numeral. So, the decimal is causing the harm. What you can do is, float
the value before calling the long
. If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just been fine with using int
to provide the key as well.
So, the answer is long(float('234.89'))
or it could just be int(float('234.89'))
if you are not using large integers. Also note that this difference does not arise in Python 3, because int is upgraded to long by default. All integers are long in python3 and call to covert is just int
setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").
From the command line, you can type
python setup.py --help
...to get a list of commands. What you are looking to do is...
python setup.py install
how can we collect the first Key "Value" (i.e 33)
By using youMap.get(keyYouHave)
, you can get the value of it.
want to store the Both "Key" and "Value" in separate variable
Yes, you can assign that to a variable.
Wait .........it's not over.
If you(business logic) are depending on the order of insertions and retrieving, you are going to see weird results. Map is not ordered they won't store in an order. Please be aware of that fact. Use some alternative to preserve your order. Probably a LinkedHashMap
That's the for each loop syntax. It is looping through each object in the collection returned by objectListing.getObjectSummaries()
.
I doubt my answer is in time to help you but others might find it helpful. I experienced a similar issue with a jQuery Ajax Post script that i created.
It turned out that i had a typo in the href attribute of the A tag that i was using to fire the post. I had typed href="javacsript:;" (reversing the 's' and the 'c' ).. this caused the script to try to refresh the page while the post was attempting to fire. corrected the typo and it worked perfectly fine for me.
$('#test').click(function() {_x000D_
var todayDate = moment("01.01.2019", "DD.MM.YYYY");_x000D_
var endDate = moment("08.02.2019", "DD.MM.YYYY");_x000D_
_x000D_
var result = 'Diff: ' + todayDate.diff(endDate, 'days');_x000D_
_x000D_
$('#result').html(result);_x000D_
});
_x000D_
#test {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: #ffb;_x000D_
padding: 10px;_x000D_
border: 2px solid #999;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>_x000D_
_x000D_
<div id='test'>Click Me!!!</div>_x000D_
<div id='result'></div>
_x000D_
What do I do wrong?
The source code of ToastDisplay is OK (mine is similar and works), but it will only receive something, if it is currently in foreground (you register receiver in onResume). But it can not receive anything if a different activity (in this case SendBroadcast activity) is shown.
Instead you probably want to startActivity ToastDisplay from the first activity?
BroadcastReceiver and Activity make sense in a different use case. In my application I need to receive notifications from a background GPS tracking service and show them in the activity (if the activity is in the foreground).
There is no need to register the receiver in the manifest. It would be even harmful in my use case - my receiver manipulates the UI of the activity and the UI would not be available during onReceive if the activity is not currently shown. Instead I register and unregister the receiver for activity in onResume and onPause as described in BroadcastReceiver documentation:
You can either dynamically register an instance of this class with Context.registerReceiver() or statically publish an implementation through the tag in your AndroidManifest.xml.
Actually my other answer didn't work if the target path wasn't a child of the base path.
This should work.
public class RelativePathFinder {
public static String getRelativePath(String targetPath, String basePath,
String pathSeparator) {
// find common path
String[] target = targetPath.split(pathSeparator);
String[] base = basePath.split(pathSeparator);
String common = "";
int commonIndex = 0;
for (int i = 0; i < target.length && i < base.length; i++) {
if (target[i].equals(base[i])) {
common += target[i] + pathSeparator;
commonIndex++;
}
}
String relative = "";
// is the target a child directory of the base directory?
// i.e., target = /a/b/c/d, base = /a/b/
if (commonIndex == base.length) {
relative = "." + pathSeparator + targetPath.substring(common.length());
}
else {
// determine how many directories we have to backtrack
for (int i = 1; i <= commonIndex; i++) {
relative += ".." + pathSeparator;
}
relative += targetPath.substring(common.length());
}
return relative;
}
public static String getRelativePath(String targetPath, String basePath) {
return getRelativePath(targetPath, basePath, File.pathSeparator);
}
}
public class RelativePathFinderTest extends TestCase {
public void testGetRelativePath() {
assertEquals("./stuff/xyz.dat", RelativePathFinder.getRelativePath(
"/var/data/stuff/xyz.dat", "/var/data/", "/"));
assertEquals("../../b/c", RelativePathFinder.getRelativePath("/a/b/c",
"/a/x/y/", "/"));
}
}
Be aware that changing locale is process-wide and not thread safe (iow., can have side effects or can affect other code executed within the same process).
My proposition: check out the Babel package. Some means of integrating with Django templates are available.
This might not be the simplest answer as compared to using array_values().
Try this
$array = array( 0 => 'string1', 2 => 'string2', 4 => 'string3', 5 => 'string4');
$arrays =$array;
print_r($array);
$array=array();
$i=0;
foreach($arrays as $k => $item)
{
$array[$i]=$item;
unset($arrays[$k]);
$i++;
}
print_r($array);
Here simple example to create pandas dataframe by using numpy array.
import numpy as np
import pandas as pd
# create an array
var1 = np.arange(start=1, stop=21, step=1).reshape(-1)
var2 = np.random.rand(20,1).reshape(-1)
print(var1.shape)
print(var2.shape)
dataset = pd.DataFrame()
dataset['col1'] = var1
dataset['col2'] = var2
dataset.head()
Well, once you have your font, you can invoke deriveFont
. For example,
helvetica = helvetica.deriveFont(Font.BOLD, 12f);
Changes the font's style to bold and its size to 12 points.
The below solution solved my problem and also kept the default values
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).find('input[type="text"],input[type="email"],textarea,select').each(function() {
if (this.defaultValue != '' || this.value != this.defaultValue) {
this.value = this.defaultValue;
} else { this.value = ''; }
});
});