I periodically search for a satisfactory answer to this, but no luck so far. I use soapUI + requests + manual labour.
I gave up and used Java the last time I needed to do this, and simply gave up a few times the last time I wanted to do this, but it wasn't essential.
Having successfully used the requests library last year with Project Place's RESTful API, it occurred to me that maybe I could just hand-roll the SOAP requests I want to send in a similar way.
Turns out that's not too difficult, but it is time consuming and prone to error, especially if fields are inconsistently named (the one I'm currently working on today has 'jobId', JobId' and 'JobID'. I use soapUI to load the WSDL to make it easier to extract endpoints etc and perform some manual testing. So far I've been lucky not to have been affected by changes to any WSDL that I'm using.
Need to do normal
forever start script.js
to start, and to check console/error logs use
forever logs
this will print list of all logs being stored by forever
and then you can use tail -f /path/to/logs/file.log
and this will print live logs to your window. hit ctrl+z to stop logs print.
you can split a string by line break by using the following statement :
String textStr[] = yourString.split("\\r?\\n");
you can split a string by Whitespace by using the following statement :
String textStr[] = yourString.split("\\s+");
I've made an alternative to the other good answers on here that uses PowerShell, but mine also saves the list to a file. Will share it here in case anyone else needs wants something like that.
Warning: Code overwrites "longfilepath.txt" in the current working directory. I know it's unlikely you'd have one already, but just in case!
Purposely wanted it in a single line:
Out-File longfilepath.txt ; cmd /c "dir /b /s /a" | ForEach-Object { if ($_.length -gt 250) {$_ | Out-File -append longfilepath.txt}}
Detailed instructions:
cat longfilepath.txt | sort
Explanation:
Out-File longfilepath.txt ;
– Create (or overwrite) a blank file titled 'longfilepath.txt'. Semi-colon to separate commands.
cmd /c "dir /b /s /a" |
– Run dir command on PowerShell, /a
to show all files including hidden files. |
to pipe.
ForEach-Object { if ($_.length -gt 250) {$_ | Out-File -append longfilepath.txt}}
– For each line (denoted as $_), if the length is greater than 250, append that line to the file.
You can use:
\set list '''foobar'''
SELECT * FROM dbo.PubLists WHERE name = :list;
That will do
You also can do like this:
default: &default
adapter: mysql2
encoding: utf8
username: root
password:
host: 127.0.0.1
port: 3306
development:
<<: *default
database: development_db_name
test:
<<: *default
database: test_db_name
production:
<<: *default
database: production_db_name
The simplest way (java.specification.version):
double version = Double.parseDouble(System.getProperty("java.specification.version"));
if (version == 1.5) {
// 1.5 specific code
} else {
// ...
}
or something like (java.version):
String[] javaVersionElements = System.getProperty("java.version").split("\\.");
int major = Integer.parseInt(javaVersionElements[1]);
if (major == 5) {
// 1.5 specific code
} else {
// ...
}
or if you want to break it all up (java.runtime.version):
String discard, major, minor, update, build;
String[] javaVersionElements = System.getProperty("java.runtime.version").split("\\.|_|-b");
discard = javaVersionElements[0];
major = javaVersionElements[1];
minor = javaVersionElements[2];
update = javaVersionElements[3];
build = javaVersionElements[4];
I needed to do a count of a very complex query with many joins. I was using the joins as filters, so I only wanted to know the count of the actual objects. count() was insufficient, but I found the answer in the docs here:
http://docs.sqlalchemy.org/en/latest/orm/tutorial.html
The code would look something like this (to count user objects):
from sqlalchemy import func
session.query(func.count(User.id)).scalar()
Here is a bare bones version:
Let's say that you have a date in Cell A1 in the format you described. For example: 19760210
.
Then this formula will give you the date you want:
=DATE(LEFT(A1,4),MID(A1,5,2),RIGHT(A1,2)).
On my system (Excel 2010) it works with strings or floats.
No, you don't need to copy all 387 constructors to Bar and Bah. Bar and Bah can have as many or as few constructors as you want independent of how many you define on Foo. For example, you could choose to have just one Bar constructor which constructs Foo with Foo's 212th constructor.
Yes, any constructors you change in Foo that Bar or Bah depend on will require you to modify Bar and Bah accordingly.
No, there is no way in .NET to inherit constructors. But you can achieve code reuse by calling a base class's constructor inside the subclass's constructor or by calling a virtual method you define (like Initialize()).
Use changelists. The advantage over specifying files is that you can visualize and confirm everything you wanted is actually included before you commit.
$ svn changelist fix-issue-237 foo.c
Path 'foo.c' is now a member of changelist 'fix-issue-237'.
That done, svn now keeps things separate for you. This helps when you're juggling multiple changes
$ svn status
A bar.c
A baz.c
--- Changelist 'fix-issue-237':
A foo.c
Finally, tell it to commit what you wanted changed.
$ svn commit --changelist fix-issue-237 -m "Issue 237"
You can try VSCommands extension from Visual Studio Gallery. Latest release allows you to select two file and compare them:
In cs file
DataTable employeeData = CreateDataTable();
gridEmployees.DataContext = employeeData.DefaultView;
In xaml file
<DataGrid Name="gridEmployees" ItemsSource="{Binding}">
Since you say you want to access by position once your data is read in, you should know about R's subsetting/ indexing functions.
The easiest is
df[row,column]
#example
df[1:5,] #rows 1:5, all columns
df[,5] #all rows, column 5.
Other methods are here. I personally use the dplyr package for intuitive data manipulation (not by position).
use: docker container stop $(docker container ls -q --filter ancestor=mongo)
(base) :~ user$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d394144acf3a mongo "docker-entrypoint.s…" 15 seconds ago Up 14 seconds 0.0.0.0:27017->27017/tcp magical_nobel
(base) :~ user$ docker container stop $(docker container ls -q --filter ancestor=mongo)
d394144acf3a
(base) :~ user$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
(base) :~ user$
From the official documentation regarding the Formatter class:
The constructor takes two optional arguments: a message format string and a date format string.
So change
# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")
to
# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s",
"%Y-%m-%d %H:%M:%S")
In that case you should use ListBox
control instead of dropdown and Set the SelectionMode
property to Multiple
<asp:ListBox runat="server" SelectionMode="Multiple" >
<asp:ListItem Text="test1"></asp:ListItem>
<asp:ListItem Text="test2"></asp:ListItem>
<asp:ListItem Text="test3"></asp:ListItem>
</asp:ListBox>
You can use max() to get the max value. The max function can also return the index of the maximum value in the vector. To get this, assign the result of the call to max to a two element vector instead of just a single variable.
e.g. z is your array,
>> [x, y] = max(z)
x =
7
y =
4
Here, 7 is the largest number at the 4th position(index).
You can get the current username on Windows by going through the Windows API, although it's a bit cumbersome to invoke via the ctypes FFI (GetCurrentProcess ? OpenProcessToken ? GetTokenInformation ? LookupAccountSid).
I wrote a small module that can do this straight from Python, getuser.py. Usage:
import getuser
print(getuser.lookup_username())
It works on both Windows and *nix (the latter uses the pwd
module as described in the other answers).
my_string := 'Hello,' + #13#10 + 'world!';
#13#10
is the CR/LF characters in decimal
I'm on Ubuntu 16.04, and upgraded to Python 3.7. Here is the error that I had when trying to add a PPA
sudo add-apt-repository ppa:ubuntu-toolchain-r/test
Traceback (most recent call last):
File "/usr/bin/add-apt-repository", line 11, in <module>
from softwareproperties.SoftwareProperties import SoftwareProperties, shortcut_handler
File "/usr/lib/python3/dist-packages/softwareproperties/SoftwareProperties.py", line 27, in <module>
import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'
I was able to fix this error by making symbolic link with my initial python 3.4 apt_pkg.cpython-34m-x86_64-linux-gnu.so by creating the following symbolic link
sudo ln -s apt_pkg.cpython-34m-x86_64-linux-gnu.so apt_pkg.so
It's impossible if the method is declared in the derived class as overrides
. to do that, the method in the derived class should be declared as new
:
public class Base {
public virtual string X() {
return "Base";
}
}
public class Derived1 : Base
{
public new string X()
{
return "Derived 1";
}
}
public class Derived2 : Base
{
public override string X() {
return "Derived 2";
}
}
Derived1 a = new Derived1();
Base b = new Derived1();
Base c = new Derived2();
a.X(); // returns Derived 1
b.X(); // returns Base
c.X(); // returns Derived 2
You're using Comparators
incorrectly.
Collections.sort(movieItems, new Comparator<Movie>(){
public int compare (Movie m1, Movie m2){
return m1.getDate().compareTo(m2.getDate());
}
});
This is one "trick" you can do since your out of an async function so can't use await keywork
Do what you want to do with vm.feed inside a setTimeout
vm.feed = getFeed().then(function(data) {return data;});
setTimeout(() => {
// do you stuf here
// after the time you promise will be revolved or rejected
// if you need some of the values in here immediately out of settimeout
// might occur an error if promise wore not yet resolved or rejected
console.log("vm.feed",vm.feed);
}, 100);
Swift 4.1
I have changed from this In Swift 3
let str = "Welcome "
let welcomeAttribute = [ NSForegroundColorAttributeName: UIColor.blue()]
let welcomeAttrString = NSMutableAttributedString(string: str, attributes: welcomeAttribute)
And this in Swift 4.0
let str = "Welcome "
let welcomeAttribute = [ NSAttributedStringKey.foregroundColor: UIColor.blue()]
let welcomeAttrString = NSMutableAttributedString(string: str, attributes: welcomeAttribute)
to Swift 4.1
let str = "Welcome "
let welcomeAttribute = [ NSAttributedStringKey(rawValue: NSForegroundColorAttributeName): UIColor.blue()]
let welcomeAttrString = NSMutableAttributedString(string: str, attributes: welcomeAttribute)
Works fine
Add this in your values/styles.xml
<style name="YourCustomTheme" parent="Theme.AppCompat.Light.NoActionBar">
</style>
<style name="AppBaseTheme" parent="YourCustomTheme">
</style>
<style name="AppTheme" parent="AppBaseTheme">
</style>
And add the following code in your values-v11/styles.xml and values-v14/styles.xml
<style name="AppBaseTheme" parent="YourCustomTheme">
</style>
Thats it. It will work.
For me simply run:
npm install cross-env
was enough
The issue is that you're not saving the mysqli connection. Change your connect to:
$aVar = mysqli_connect('localhost','tdoylex1_dork','dorkk','tdoylex1_dork');
And then include it in your query:
$query1 = mysqli_query($aVar, "SELECT name1 FROM users
ORDER BY RAND()
LIMIT 1");
$aName1 = mysqli_fetch_assoc($query1);
$name1 = $aName1['name1'];
Also don't forget to enclose your connections variables as strings as I have above. This is what's causing the error but you're using the function wrong, mysqli_query returns a query object but to get the data out of this you need to use something like mysqli_fetch_assoc http://php.net/manual/en/mysqli-result.fetch-assoc.php to actually get the data out into a variable as I have above.
Too late, just in case some one is looking for another way:
void Main()
{
string jsonString = @"{
'Stores': [
'Lambton Quay',
'Willis Street'
],
'Manufacturers': [
{
'Name': 'Acme Co',
'Products': [
{
'Name': 'Anvil',
'Price': 50
}
]
},
{
'Name': 'Contoso',
'Products': [
{
'Name': 'Elbow Grease',
'Price': 99.95
},
{
'Name': 'Headlight Fluid',
'Price': 4
}
]
}
]
}";
Product product = new Product();
//Serializing to Object
Product obj = JObject.Parse(jsonString).SelectToken("$.Manufacturers[?(@.Name == 'Acme Co' && @.Name != 'Contoso')]").ToObject<Product>();
Console.WriteLine(obj);
}
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
}
The referenced field must be a "Key" in the referenced table, not necessarily a primary key. So the "car_id" should either be a primary key or be defined with NOT NULL and UNIQUE constraints in the "Cars" table.
And moreover, both fields must be of the same type and collation.
I was also getting same issue as i tried using value 0 in non-based indexing,i.e starting with 1, not with zero
<ImageButton android:src="@drawable/image_btn_src" ... />
image_btn_src.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/icon_pressed"/>
<item android:state_pressed="false" android:drawable="@drawable/icon_unpressed"/>
</selector>
By default compiler tries to call parameterless constructor of base class.
In case if the base class doesn't have a parameterless constructor, you have to explicitly call it yourself:
public child(int i) : base(i){
Console.WriteLine("child");}
None, False and True
all are available within template tags and filters. None, False
, the empty string ('', "", """"""
) and empty lists/tuples all evaluate to False
when evaluated by if
, so you can easily do
{% if profile.user.first_name == None %}
{% if not profile.user.first_name %}
A hint: @fabiocerqueira is right, leave logic to models, limit templates to be the only presentation layer and calculate stuff like that in you model. An example:
# someapp/models.py
class UserProfile(models.Model):
user = models.OneToOneField('auth.User')
# other fields
def get_full_name(self):
if not self.user.first_name:
return
return ' '.join([self.user.first_name, self.user.last_name])
# template
{{ user.get_profile.get_full_name }}
Hope this helps :)
What about creating an additional wrapper class?
package com.naveen.research.sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public abstract class PreparedStatementWrapper implements AutoCloseable {
protected PreparedStatement stat;
public PreparedStatementWrapper(Connection con, String query, Object ... params) throws SQLException {
this.stat = con.prepareStatement(query);
this.prepareStatement(params);
}
protected abstract void prepareStatement(Object ... params) throws SQLException;
public ResultSet executeQuery() throws SQLException {
return this.stat.executeQuery();
}
public int executeUpdate() throws SQLException {
return this.stat.executeUpdate();
}
@Override
public void close() {
try {
this.stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Then in the calling class you can implement prepareStatement method as:
try (Connection con = DriverManager.getConnection(JDBC_URL, prop);
PreparedStatementWrapper stat = new PreparedStatementWrapper(con, query,
new Object[] { 123L, "TEST" }) {
@Override
protected void prepareStatement(Object... params) throws SQLException {
stat.setLong(1, Long.class.cast(params[0]));
stat.setString(2, String.valueOf(params[1]));
}
};
ResultSet rs = stat.executeQuery();) {
while (rs.next())
System.out.println(String.format("%s, %s", rs.getString(2), rs.getString(1)));
} catch (SQLException e) {
e.printStackTrace();
}
I might suggest this, as a more gracefully degrading solution, using preventDefault
:
$('a').click(function(e) {
e.preventDefault(); //stop the browser from following
window.location.href = 'uploads/file.doc';
});
<a href="no-script.html">Download now!</a>
Even if there's no Javascript, at least this way the user will get some feedback.
As Umesh Patil answer have comment say that there is problem. I try to edit answer and get reject. And get suggest to post new answer. This code should solve problem they have (Shashi Roy, Gaven, John Higgins).
<html>
<head>
<script type="text/javascript">
function CheckColors(val){
var element=document.getElementById('othercolor');
if(val=='others')
element.style.display='block';
else
element.style.display='none';
}
</script>
</head>
<body>
<select name="color" onchange='CheckColors(this.value);'>
<option>pick a color</option>
<option value="red">RED</option>
<option value="blue">BLUE</option>
<option value="others">others</option>
</select>
<input type="text" name="othercolor" id="othercolor" style='display:none;'/>
</body>
</html>
Try:
int sum = lst.stream().filter(o -> o.field > 10).mapToInt(o -> o.field).sum();
Try this......pass in the number to be rounded off and it will round off to the nearest tenth.hope it helps....
round($num, 1);
There are two solutions to this:
a) Set your PATH variable to include "/usr/local/bin"
export PATH="$PATH:/usr/local/bin"
b) Create a symlink to "/usr/bin" which is already in your PATH
ln -s /usr/bin/nodejs /usr/bin/node
I hope it helps.
You cant style the alt attribute directly in css. However the alt will inherit the styles of the item the alt is on or what is inherited by its parent:
<div style="background-color:black; height: 50px; width: 50px; color:white;">_x000D_
<img src="ouch" alt="here i am"/>_x000D_
<div>
_x000D_
In the above example, the alt text will be black. However with the color:white the alt text is white.
Here is the code, I don't think there is any method in SE.
It basically converts number to string and parses String and associates it with the weight
for example
1000
1
is treated as thousand position and 1
gets mapped to "one"
and thousand because of position
This is the code from the website:
English
import java.text.DecimalFormat;
public class EnglishNumberToWords {
private static final String[] tensNames = {
"",
" ten",
" twenty",
" thirty",
" forty",
" fifty",
" sixty",
" seventy",
" eighty",
" ninety"
};
private static final String[] numNames = {
"",
" one",
" two",
" three",
" four",
" five",
" six",
" seven",
" eight",
" nine",
" ten",
" eleven",
" twelve",
" thirteen",
" fourteen",
" fifteen",
" sixteen",
" seventeen",
" eighteen",
" nineteen"
};
private EnglishNumberToWords() {}
private static String convertLessThanOneThousand(int number) {
String soFar;
if (number % 100 < 20){
soFar = numNames[number % 100];
number /= 100;
}
else {
soFar = numNames[number % 10];
number /= 10;
soFar = tensNames[number % 10] + soFar;
number /= 10;
}
if (number == 0) return soFar;
return numNames[number] + " hundred" + soFar;
}
public static String convert(long number) {
// 0 to 999 999 999 999
if (number == 0) { return "zero"; }
String snumber = Long.toString(number);
// pad with "0"
String mask = "000000000000";
DecimalFormat df = new DecimalFormat(mask);
snumber = df.format(number);
// XXXnnnnnnnnn
int billions = Integer.parseInt(snumber.substring(0,3));
// nnnXXXnnnnnn
int millions = Integer.parseInt(snumber.substring(3,6));
// nnnnnnXXXnnn
int hundredThousands = Integer.parseInt(snumber.substring(6,9));
// nnnnnnnnnXXX
int thousands = Integer.parseInt(snumber.substring(9,12));
String tradBillions;
switch (billions) {
case 0:
tradBillions = "";
break;
case 1 :
tradBillions = convertLessThanOneThousand(billions)
+ " billion ";
break;
default :
tradBillions = convertLessThanOneThousand(billions)
+ " billion ";
}
String result = tradBillions;
String tradMillions;
switch (millions) {
case 0:
tradMillions = "";
break;
case 1 :
tradMillions = convertLessThanOneThousand(millions)
+ " million ";
break;
default :
tradMillions = convertLessThanOneThousand(millions)
+ " million ";
}
result = result + tradMillions;
String tradHundredThousands;
switch (hundredThousands) {
case 0:
tradHundredThousands = "";
break;
case 1 :
tradHundredThousands = "one thousand ";
break;
default :
tradHundredThousands = convertLessThanOneThousand(hundredThousands)
+ " thousand ";
}
result = result + tradHundredThousands;
String tradThousand;
tradThousand = convertLessThanOneThousand(thousands);
result = result + tradThousand;
// remove extra spaces!
return result.replaceAll("^\\s+", "").replaceAll("\\b\\s{2,}\\b", " ");
}
/**
* testing
* @param args
*/
public static void main(String[] args) {
System.out.println("*** " + EnglishNumberToWords.convert(0));
System.out.println("*** " + EnglishNumberToWords.convert(1));
System.out.println("*** " + EnglishNumberToWords.convert(16));
System.out.println("*** " + EnglishNumberToWords.convert(100));
System.out.println("*** " + EnglishNumberToWords.convert(118));
System.out.println("*** " + EnglishNumberToWords.convert(200));
System.out.println("*** " + EnglishNumberToWords.convert(219));
System.out.println("*** " + EnglishNumberToWords.convert(800));
System.out.println("*** " + EnglishNumberToWords.convert(801));
System.out.println("*** " + EnglishNumberToWords.convert(1316));
System.out.println("*** " + EnglishNumberToWords.convert(1000000));
System.out.println("*** " + EnglishNumberToWords.convert(2000000));
System.out.println("*** " + EnglishNumberToWords.convert(3000200));
System.out.println("*** " + EnglishNumberToWords.convert(700000));
System.out.println("*** " + EnglishNumberToWords.convert(9000000));
System.out.println("*** " + EnglishNumberToWords.convert(9001000));
System.out.println("*** " + EnglishNumberToWords.convert(123456789));
System.out.println("*** " + EnglishNumberToWords.convert(2147483647));
System.out.println("*** " + EnglishNumberToWords.convert(3000000010L));
/*
*** zero
*** one
*** sixteen
*** one hundred
*** one hundred eighteen
*** two hundred
*** two hundred nineteen
*** eight hundred
*** eight hundred one
*** one thousand three hundred sixteen
*** one million
*** two millions
*** three millions two hundred
*** seven hundred thousand
*** nine millions
*** nine millions one thousand
*** one hundred twenty three millions four hundred
** fifty six thousand seven hundred eighty nine
*** two billion one hundred forty seven millions
** four hundred eighty three thousand six hundred forty seven
*** three billion ten
**/
}
}
Français Quite different than the english version but french is a lot more difficult!
package com.rgagnon.howto;
import java.text.*;
class FrenchNumberToWords {
private static final String[] dizaineNames = {
"",
"",
"vingt",
"trente",
"quarante",
"cinquante",
"soixante",
"soixante",
"quatre-vingt",
"quatre-vingt"
};
private static final String[] uniteNames1 = {
"",
"un",
"deux",
"trois",
"quatre",
"cinq",
"six",
"sept",
"huit",
"neuf",
"dix",
"onze",
"douze",
"treize",
"quatorze",
"quinze",
"seize",
"dix-sept",
"dix-huit",
"dix-neuf"
};
private static final String[] uniteNames2 = {
"",
"",
"deux",
"trois",
"quatre",
"cinq",
"six",
"sept",
"huit",
"neuf",
"dix"
};
private FrenchNumberToWords() {}
private static String convertZeroToHundred(int number) {
int laDizaine = number / 10;
int lUnite = number % 10;
String resultat = "";
switch (laDizaine) {
case 1 :
case 7 :
case 9 :
lUnite = lUnite + 10;
break;
default:
}
// séparateur "-" "et" ""
String laLiaison = "";
if (laDizaine > 1) {
laLiaison = "-";
}
// cas particuliers
switch (lUnite) {
case 0:
laLiaison = "";
break;
case 1 :
if (laDizaine == 8) {
laLiaison = "-";
}
else {
laLiaison = " et ";
}
break;
case 11 :
if (laDizaine==7) {
laLiaison = " et ";
}
break;
default:
}
// dizaines en lettres
switch (laDizaine) {
case 0:
resultat = uniteNames1[lUnite];
break;
case 8 :
if (lUnite == 0) {
resultat = dizaineNames[laDizaine];
}
else {
resultat = dizaineNames[laDizaine]
+ laLiaison + uniteNames1[lUnite];
}
break;
default :
resultat = dizaineNames[laDizaine]
+ laLiaison + uniteNames1[lUnite];
}
return resultat;
}
private static String convertLessThanOneThousand(int number) {
int lesCentaines = number / 100;
int leReste = number % 100;
String sReste = convertZeroToHundred(leReste);
String resultat;
switch (lesCentaines) {
case 0:
resultat = sReste;
break;
case 1 :
if (leReste > 0) {
resultat = "cent " + sReste;
}
else {
resultat = "cent";
}
break;
default :
if (leReste > 0) {
resultat = uniteNames2[lesCentaines] + " cent " + sReste;
}
else {
resultat = uniteNames2[lesCentaines] + " cents";
}
}
return resultat;
}
public static String convert(long number) {
// 0 à 999 999 999 999
if (number == 0) { return "zéro"; }
String snumber = Long.toString(number);
// pad des "0"
String mask = "000000000000";
DecimalFormat df = new DecimalFormat(mask);
snumber = df.format(number);
// XXXnnnnnnnnn
int lesMilliards = Integer.parseInt(snumber.substring(0,3));
// nnnXXXnnnnnn
int lesMillions = Integer.parseInt(snumber.substring(3,6));
// nnnnnnXXXnnn
int lesCentMille = Integer.parseInt(snumber.substring(6,9));
// nnnnnnnnnXXX
int lesMille = Integer.parseInt(snumber.substring(9,12));
String tradMilliards;
switch (lesMilliards) {
case 0:
tradMilliards = "";
break;
case 1 :
tradMilliards = convertLessThanOneThousand(lesMilliards)
+ " milliard ";
break;
default :
tradMilliards = convertLessThanOneThousand(lesMilliards)
+ " milliards ";
}
String resultat = tradMilliards;
String tradMillions;
switch (lesMillions) {
case 0:
tradMillions = "";
break;
case 1 :
tradMillions = convertLessThanOneThousand(lesMillions)
+ " million ";
break;
default :
tradMillions = convertLessThanOneThousand(lesMillions)
+ " millions ";
}
resultat = resultat + tradMillions;
String tradCentMille;
switch (lesCentMille) {
case 0:
tradCentMille = "";
break;
case 1 :
tradCentMille = "mille ";
break;
default :
tradCentMille = convertLessThanOneThousand(lesCentMille)
+ " mille ";
}
resultat = resultat + tradCentMille;
String tradMille;
tradMille = convertLessThanOneThousand(lesMille);
resultat = resultat + tradMille;
return resultat;
}
public static void main(String[] args) {
System.out.println("*** " + FrenchNumberToWords.convert(0));
System.out.println("*** " + FrenchNumberToWords.convert(9));
System.out.println("*** " + FrenchNumberToWords.convert(19));
System.out.println("*** " + FrenchNumberToWords.convert(21));
System.out.println("*** " + FrenchNumberToWords.convert(28));
System.out.println("*** " + FrenchNumberToWords.convert(71));
System.out.println("*** " + FrenchNumberToWords.convert(72));
System.out.println("*** " + FrenchNumberToWords.convert(80));
System.out.println("*** " + FrenchNumberToWords.convert(81));
System.out.println("*** " + FrenchNumberToWords.convert(89));
System.out.println("*** " + FrenchNumberToWords.convert(90));
System.out.println("*** " + FrenchNumberToWords.convert(91));
System.out.println("*** " + FrenchNumberToWords.convert(97));
System.out.println("*** " + FrenchNumberToWords.convert(100));
System.out.println("*** " + FrenchNumberToWords.convert(101));
System.out.println("*** " + FrenchNumberToWords.convert(110));
System.out.println("*** " + FrenchNumberToWords.convert(120));
System.out.println("*** " + FrenchNumberToWords.convert(200));
System.out.println("*** " + FrenchNumberToWords.convert(201));
System.out.println("*** " + FrenchNumberToWords.convert(232));
System.out.println("*** " + FrenchNumberToWords.convert(999));
System.out.println("*** " + FrenchNumberToWords.convert(1000));
System.out.println("*** " + FrenchNumberToWords.convert(1001));
System.out.println("*** " + FrenchNumberToWords.convert(10000));
System.out.println("*** " + FrenchNumberToWords.convert(10001));
System.out.println("*** " + FrenchNumberToWords.convert(100000));
System.out.println("*** " + FrenchNumberToWords.convert(2000000));
System.out.println("*** " + FrenchNumberToWords.convert(3000000000L));
System.out.println("*** " + FrenchNumberToWords.convert(2147483647));
/*
*** OUTPUT
*** zéro
*** neuf
*** dix-neuf
*** vingt et un
*** vingt-huit
*** soixante et onze
*** soixante-douze
*** quatre-vingt
*** quatre-vingt-un
*** quatre-vingt-neuf
*** quatre-vingt-dix
*** quatre-vingt-onze
*** quatre-vingt-dix-sept
*** cent
*** cent un
*** cent dix
*** cent vingt
*** deux cents
*** deux cent un
*** deux cent trente-deux
*** neuf cent quatre-vingt-dix-neuf
*** mille
*** mille un
*** dix mille
*** dix mille un
*** cent mille
*** deux millions
*** trois milliards
*** deux milliards cent quarante-sept millions
** quatre cent quatre-vingt-trois mille six cent quarante-sept
*/
}
}
You can handle "dollar and cent" conversion by calling the "convert" method two times.
String phrase = "12345.67" ;
Float num = new Float( phrase ) ;
int dollars = (int)Math.floor( num ) ;
int cent = (int)Math.floor( ( num - dollars ) * 100.0f ) ;
String s = "$ " + EnglishNumberToWords.convert( dollars ) + " and "
+ EnglishNumberToWords.convert( cent ) + " cents" ;
Another way to use a built-in function of your DBMS (if available). For Oracle
SQL> select to_char(to_date(873,'J'), 'JSP') as converted_form from dual;
CONVERTED_FORM
---------------------------
EIGHT HUNDRED SEVENTY-THREE
SQL>
'JSP' means :
J : the Julian format.
SP : spells the word for the number passed to to_date
In Fedora 25, it turned out to be an SE Linux issue, and the notification gave this solution which worked for me.
setsebool -P httpd_read_user_content 1
Also take a look at awesome project aqtinstall
https://github.com/miurahr/aqtinstall/ (it can install any Qt version on Linux, Mac and Windows machines without any interaction!) and GitHub Action that uses this tool: https://github.com/jurplel/install-qt-action
As others already replied, it's late to write unit tests, but not too late. The question is whether your code is testable or not. Indeed, it's not easy to put existing code under test, there is even a book about this: Working Effectively with Legacy Code (see key points or precursor PDF).
Now writing the unit tests or not is your call. You just need to be aware that it could be a tedious task. You might tackle this to learn unit-testing or consider writing acceptance (end-to-end) tests first, and start writing unit tests when you'll change the code or add new feature to the project.
So by adding the #!/bin/sh
will allow you to execute with no option.
It also helped me in fixing an issue where I was executing bash script from Jenkins master on my Linux slave. By just adding #!/bin/bash
above my actual script in "Execute Shell" block it fixed my issue as otherwise it was executing windows git provided version of bash shell that was giving an error.
This answer is useful to them who want click to chat whatsapp in website to redirect web.whatsapp.com with default content or message and in mobile device to open in whatsapp in mobile app with default content to text bar in app.
also add jquery link.
<a target="_blank" title="Contact Us On WhatsApp" href="https://web.whatsapp.com/send?phone=+919581880892&text=Hi, I would like to get more information.." class="whatsapplink hidemobile" style="background-color:#2DC100">
<i class="fa fa-fw fa-whatsapp" style="color:#fff"></i>
<span style="color:#fff">
Contact Us On WhatsApp </span>
</a>
<a target="_blank" title="Contact Us On WhatsApp" href="https://api.whatsapp.com/send?phone=+919581880892&text=Hi,%20I%20would%20like%20to%20get%20more%20information.." class="whatsapplink hideweb" style="background-color:#2DC100">
<i class="fa fa-fw fa-whatsapp" style="color:#fff"></i>
<span style="color:#fff">
Contact Us On WhatsApp </span>
</a>
<script type="text/javascript">
var mobile = (/iphone|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));
if (mobile) {
$('.hidemobile').css('display', 'none'); // OR you can use $('.hidemobile').hide();
}
else
{
$('.hideweb').css('display', 'none'); // OR you can use $('.hideweb').hide();
}
</script>
You can use prettytable to render the table as text. The trick is to convert the data_frame to an in-memory csv file and have prettytable read it. Here's the code:
from StringIO import StringIO
import prettytable
output = StringIO()
data_frame.to_csv(output)
output.seek(0)
pt = prettytable.from_csv(output)
print pt
If you're using Win10 with Xampp server installed, then you can find the data folder in C:\xampp\mysql\data
Inside the data folder, each database has its own folder which in turn contains the .frm, .myi and .myd files which represent for a single table in the database.
If for instance, you created a database with the name: myschool and inside the database, you have three tables with the names:
Then, you will have for the Nursery table: nursery.frm, nursery.myi and nursery.myd. Same will go for the Primary and Secondary tables. Thus, in the I mentioned here, you will a total of 9 files inside the database folder named myschool.
You can then copy the database folder and use it in your new mysql installation data folder.
I hope this helps.
Best regards.
If the situation is an urgent one, and you just want to do what the questioner asked in a quick and dirty way, assuming your project is under a directory called, for example, "my project":
QUICK AND DIRTY: depending on the circumstances, quick and dirty may in fact be very GOOD. What my solution here does is NOT replace irreversibly the files you have in your working directory with files hauled up/extracted from the depths of the git repository lurking beneath your .git/ directory using fiendishly clever and diabolically powerful git commands, of which there are many. YOU DO NOT HAVE TO DO SUCH DEEP-SEA DIVING TO RECOVER what may appear to be a disastrous situation, and attempting to do so without sufficient expertise may prove fatal.
Copy the whole directory and call it something else, like "my project - copy". Assuming your git repository ("repo") files are under the "my project" directory (the default place for them, under a directory called ".git"), you will now have copied both your work files and your repo files.
Do this in the directory "my project":
.../my project $ git reset --hard [first-4-letters&numbers-of-commit's-SHA]
This will return the state of the repo under "my project" to what it was when you made that commit (a "commit" means a snapshot of your working files). All commits since then will be lost forever under "my project", BUT... they will still be present in the repo under "my project - copy" since you copied all those files - including the ones under .../.git/.
You then have two versions on your system... you can examine or copy or modify files of interest, or whatever, from the previous commit. You can completely discard the files under "my project - copy", if you have decided the new work since the restored commit was going nowhere...
The obvious thing if you want to carry on with the state of the project without actually discarding the work since this retrieved commit is to rename your directory again: Delete the project containing the retrieved commit (or give it a temporary name) and rename your "my project - copy" directory back to "my project". Then maybe try to understand some of the other answers here, and probably do another commit fairly soon.
Git is a brilliant creation but absolutely no-one is able to just "pick it up on the fly": also people who try to explain it far too often assume prior knowledge of other VCS [Version Control Systems] and delve far too deep far too soon, and commit other crimes, like using interchangeable terms for "checking out" - in ways which sometimes appear almost calculated to confuse a beginner.
To save yourself much stress, learn from my scars. You have to pretty much have to read a book on Git - I'd recommend "Version Control with Git". Do it sooner rather than later. If you do, bear in mind that much of the complexity of Git comes from branching and then remerging: you can skip those parts in any book. From your question there's no reason why people should be blinding you with science.
Especially if, for example, this is a desperate situation and you're a newbie with Git!
PS: One other thought: It is (now) actually quite simple to keep the Git repo in a directory other than the one with the working files. This would mean you would not have to copy the entire Git repository using the above quick & dirty solution. See the answer by Fryer using --separate-git-dir
here. Be warned, though: If you have a "separate-directory" repository which you don't copy, and you do a hard reset, all versions subsequent to the reset commit will be lost forever, unless you have, as you absolutely should, regularly backed up your repository, preferably to the Cloud (e.g. Google Drive) among other places.
On this subject of "backing up to the Cloud", the next step is to open an account (free of course) with GitHub or (better in my view) GitLab. You can then regularly do a git push
command to make your Cloud repo up-to-date "properly". But again, talking about this may be too much too soon.
It's a matter of scope. In short, global variables should be avoided so:
You either need to pass it as a parameter:
$data = 'My data';
function menugen($data)
{
echo $data;
}
Or have it in a class and access it
class MyClass
{
private $data = "";
function menugen()
{
echo this->data;
}
}
See @MatteoTassinari answer as well, as you can mark it as global to access it, but global variables are generally not required, so it would be wise to re-think your coding.
On SQL Server 2012, you can use the following stored procedure:
sp_columns '<table name>'
For example, given a database table named users:
sp_columns 'users'
I don't think there's one that's complete in the standard Java classes; HttpURLConnection
is missing quite a few codes, like HTTP 100/Continue
.
There's a complete list in the Apache HttpComponents, though:
org.apache.http.HttpStatus
(replaced org.apache.commons.HttpClient.HttpStatus
from Apache Http Client, which reached end of life)
Don't use document.write, here is workaround:
var script = document.createElement('script');
script.src = "....";
document.head.appendChild(script);
You can achieve this by adding border class of bootstrap
like for border left ,you can use border-left
working code
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-3 text-center leftspan border-right border-bottom" id="one"><h5>Rich Media Ad Production</h5><img src="images/richmedia.png"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center leftspan border-right border-bottom" id="two"><h5>Web Design & Development</h5> <img src="images/web.png" ></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center leftspan border-right border-bottom" id="three"><h5>Mobile Apps Development</h5> <img src="images/mobile.png"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center rightspan border-bottom" id="four"><h5>Creative Design</h5> <img src="images/mobile.png"> </div>
<div class="col-xs-12"><hr></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center leftspan border-right" id="five"><h5>Web Analytics</h5> <img src="images/analytics.png"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center leftspan border-right" id="six"><h5>Search Engine Marketing</h5> <img src="images/searchengine.png"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center leftspan border-right" id="seven"><h5>Mobile Apps Development</h5> <img src="images/socialmedia.png"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center rightspan" id="eight"><h5>Quality Assurance</h5> <img src="images/qa.png"></div>
<hr>
</div>
for more refrence al bootstrap classes all classes ,search for border
If you have access to SCSS files from font-awesome, you can use this simple solution:
.a:after {
// Import mixin from font-awesome/scss/mixins.scss
@include fa-icon();
// Use icon variable from font-awesome/scss/variables.scss
content: $fa-var-exclamation-triangle;
}
Acording to the docs:
Note The urllib2 module has been split across several modules in Python 3 named
urllib.request
andurllib.error
. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.
So it appears that it is impossible to do what you want but you can use appropriate python3 functions from urllib.request
.
if you use Android M:
Step 1 : adb usb
Step 2 : adb devices
Step 3 :adb tcpip 5556
Go to Settings -> About phone/tablet -> Status -> IP address.
Step 4 : adb connect ADDRESS IP OF YOUR PHONE:5556
You can use new Date().getTime()
for getting timestamps. Then you can calculate the difference between end and start and finally transform the timestamp which is ms
into s
.
const start = new Date().getTime();
const end = new Date().getTime();
const diff = end - start;
const seconds = Math.floor(diff / 1000 % 60);
As a counter point to the general thrust of the other answers. See The Many Benefits of Money…Data Type! in SQLCAT's Guide to Relational Engine
Specifically I would point out the following
Working on customer implementations, we found some interesting performance numbers concerning the money data type. For example, when Analysis Services was set to the currency data type (from double) to match the SQL Server money data type, there was a 13% improvement in processing speed (rows/sec). To get faster performance within SQL Server Integration Services (SSIS) to load 1.18 TB in under thirty minutes, as noted in SSIS 2008 - world record ETL performance, it was observed that changing the four decimal(9,2) columns with a size of 5 bytes in the TPC-H LINEITEM table to money (8 bytes) improved bulk inserting speed by 20% ... The reason for the performance improvement is because of SQL Server’s Tabular Data Stream (TDS) protocol, which has the key design principle to transfer data in compact binary form and as close as possible to the internal storage format of SQL Server. Empirically, this was observed during the SSIS 2008 - world record ETL performance test using Kernrate; the protocol dropped significantly when the data type was switched to money from decimal. This makes the transfer of data as efficient as possible. A complex data type needs additional parsing and CPU cycles to handle than a fixed-width type.
So the answer to the question is "it depends". You need to be more careful with certain arithmetical operations to preserve precision but you may find that performance considerations make this worthwhile.
If you are using the new** Gradle build system then getPackageName
will oddly return application Id, not package name. So MasterGaurav's answer is correct but he doesn't need to start off with ++
If by application id, you're referring to package name...
See more about the differences here.
** not so new at this point
++ I realize that his answer made perfect sense in 2011
pgAdmin has GUI for data import since 1.16. You have to create your table first and then you can import data easily - just right-click on the table name and click on Import.
Add the jar files on class path NOT modulepath.
Use -b:a
instead of -ab
as -ab
is outdated now, also make sure your input file path is correct.
To extract audio from a video I have used below command and its working fine.
String[] complexCommand = {"-y", "-i", inputFileAbsolutePath, "-vn", "-ar", "44100", "-ac", "2", "-b:a", "256k", "-f", "mp3", outputFileAbsolutePath};
Here,
-y
- Overwrite output files without asking.-i
- FFmpeg reads from an arbitrary number of input “files” specified by the -i
option-vn
- Disable video recording-ar
- sets the sampling rate for audio streams if encoded-ac
- Set the number of audio channels.-b:a
- Set the audio bitrate-f
- formatCheck out this for my complete sample FFmpeg android project on GitHub.
You can do this a couple of ways.
Via the "Solution Explorer"
Via the "Package Manager Console"
Install-Package Newtonsoft.Json
For more info on how to use the "Package Manager Console" check out the nuget docs.
Do everything suggested by ziesemer.
You may also want to :
The most common way to do this is something along these lines:
ul {_x000D_
list-style: none;_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
li {_x000D_
padding-left: 1em; _x000D_
text-indent: -.7em;_x000D_
}_x000D_
_x000D_
li::before {_x000D_
content: "• ";_x000D_
color: red; /* or whatever color you prefer */_x000D_
}
_x000D_
<ul>_x000D_
<li>Foo</li>_x000D_
<li>Bar</li>_x000D_
<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</li>_x000D_
</ul>
_x000D_
JSFiddle: http://jsfiddle.net/leaverou/ytH5P/
Will work in all browsers, including IE from version 8 and up.
Along with forEach
method that accepts a lambda expression we have also got stream APIs, in Java 8.
Iterate over entries (Using forEach and Streams):
sample.forEach((k,v) -> System.out.println(k + "=" + v));
sample.entrySet().stream().forEachOrdered((entry) -> {
Object currentKey = entry.getKey();
Object currentValue = entry.getValue();
System.out.println(currentKey + "=" + currentValue);
});
sample.entrySet().parallelStream().forEach((entry) -> {
Object currentKey = entry.getKey();
Object currentValue = entry.getValue();
System.out.println(currentKey + "=" + currentValue);
});
The advantage with streams is they can be parallelized easily and can be useful when we have multiple CPUs at disposal. We simply need to use parallelStream()
in place of stream()
above. With parallel streams it makes more sense to use forEach
as forEachOrdered
would make no difference in performance. If we want to iterate over keys we can use sample.keySet()
and for values sample.values()
.
Why forEachOrdered
and not forEach
with streams ?
Streams also provide forEach
method but the behaviour of forEach
is explicitly nondeterministic where as the forEachOrdered
performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. So forEach
does not guarantee that the order would be kept. Also check this for more.
::ng-deep
, >>>
and /deep/
disable view encapsulation for specific CSS rules, in other words, it gives you access to DOM elements, which are not in your component's HTML. For example, if you're using Angular Material (or any other third-party library like this), some generated elements are outside of your component's area (such as dialog) and you can't access those elements directly or using a regular CSS way. If you want to change the styles of those elements, you can use one of those three things, for example:
::ng-deep .mat-dialog {
/* styles here */
}
For now Angular team recommends making "deep" manipulations only with EMULATED view encapsulation.
"deep" manipulations are actually deprecated too, BUT it stills working for now, because Angular does pre-processing support (don't rush to refuse ::ng-deep
today, take a look at deprecation practices first).
Anyway, before following this way, I recommend you to take a look at disabling view encapsulation approach (which is not ideal too, it allows your styles to leak into other components), but in some cases, it's a better way. If you decided to disable view encapsulation, it's strongly recommended to use specific classes to avoid CSS rules intersection, and finally, avoid a mess in your stylesheets. It's really easy to disable right in the component's .ts
file:
@Component({
selector: '',
template: '',
styles: [''],
encapsulation: ViewEncapsulation.None // Use to disable CSS Encapsulation for this component
})
You can find more info about the view encapsulation in this article.
You can combine the columns without using macros. Type the following function in the formula bar:
=IF(ROW()<=COUNTA(A:A),INDEX(A:A,ROW()),IF(ROW()<=COUNTA(A:B),INDEX(B:B,ROW()-COUNTA(A:A)),IF(ROW()>COUNTA(A:C),"",INDEX(C:C,ROW()-COUNTA(A:B)))))
The statement uses 3 IF functions, because it needs to combine 3 columns:
Just Try This :
textfield.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
if(textfield.getText().length()>=5&&!(evt.getKeyChar()==KeyEvent.VK_DELETE||evt.getKeyChar()==KeyEvent.VK_BACK_SPACE)) {
getToolkit().beep();
evt.consume();
}
}
});
This is an issue if you are using 2008 management studio tools to connect to a SQL 2012 instance.
I experience this a lot if I am working on one server with SQL 2008, and trying to quickly query another server that is running SQL 2012.
I normally keep my personal workstation on the latest version of management studio (2012 in this case), and am able to administer all servers from there.
<div id="image">Example to have Background Image</div>
We need to Add the below content in Style tag:
.image {
background-image: url('C:\Users\ajai\Desktop\10.jpg');
}
If you are facing this problem in a specific module in your project, you could try opening just that module as a project and then build it. This worked for me. It was failing to generate the R file for the module when I was trying to re-build the entire project.
The element has both an attribute and a property named checked
. The property determines the current state.
The attribute is a string, and the property is a boolean. When the element is created from the HTML code, the attribute is set from the markup, and the property is set depending on the value of the attribute.
If there is no value for the attribute in the markup, the attribute becomes null
, but the property is always either true
or false
, so it becomes false
.
When you set the property, you should use a boolean value:
document.getElementById('myRadio').checked = true;
If you set the attribute, you use a string:
document.getElementById('myRadio').setAttribute('checked', 'checked');
Note that setting the attribute also changes the property, but setting the property doesn't change the attribute.
Note also that whatever value you set the attribute to, the property becomes true
. Even if you use an empty string or null
, setting the attribute means that it's checked. Use removeAttribute
to uncheck the element using the attribute:
document.getElementById('myRadio').removeAttribute('checked');
You can try Restlet edition for android:
The source can be downloaded from Restlet website:
Having said, I'd rather see developers build kick-ass apps that are well-designed and follow separation of concerns, than see them waste time arguing about MV* nonsense. And for this reason, I hereby declare AngularJS to be MVW framework - Model-View-Whatever. Where Whatever stands for "whatever works for you".
Credits : AngularJS Post - Igor Minar
Use this code everywhere for unregisterReceiver:
if (batteryNotifyReceiver != null) {
unregisterReceiver(batteryNotifyReceiver);
batteryNotifyReceiver = null;
}
Only nested classes can be static. By doing so you can use the nested class without having an instance of the outer class.
class OuterClass {
public static class StaticNestedClass {
}
public class InnerClass {
}
public InnerClass getAnInnerClass() {
return new InnerClass();
}
//This method doesn't work
public static InnerClass getAnInnerClassStatically() {
return new InnerClass();
}
}
class OtherClass {
//Use of a static nested class:
private OuterClass.StaticNestedClass staticNestedClass = new OuterClass.StaticNestedClass();
//Doesn't work
private OuterClass.InnerClass innerClass = new OuterClass.InnerClass();
//Use of an inner class:
private OuterClass outerclass= new OuterClass();
private OuterClass.InnerClass innerClass2 = outerclass.getAnInnerClass();
private OuterClass.InnerClass innerClass3 = outerclass.new InnerClass();
}
Sources :
On the same topic :
The simplest solutions seem to overlook that UTC time will be used, including highly up-voted ones. Below is a streamlined, ES6, non-jQuery version of a couple of existing answers:
const today = (function() {
const now = new Date();
const month = (now.getMonth() + 1).toString().padStart(2, '0');
const day = now.getDate().toString().padStart(2, '0');
return `${now.getFullYear()}-${month}-${day}`;
})();
console.log(today); // as of posting this answer: 2019-01-24
One possibility is when installed sql server data tools Bi, while sql server was already set up.
Solution:- 1.Just Repair the sql server with the set up instance
if solution does not work , than its worth your time meddling with services.msc
SPServices is a jQuery library which abstracts SharePoint's Web Services and makes them easier to use
It is certified for SharePoint 2007
The list of supported operations for Lists.asmx could be found here
In this example, we're grabbing all of the items in the Announcements list and displaying the Titles in a bulleted list in the tasksUL div:
<script type="text/javascript" src="filelink/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="filelink/jquery.SPServices-0.6.2.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$().SPServices({
operation: "GetListItems",
async: false,
listName: "Announcements",
CAMLViewFields: "<ViewFields><FieldRef Name='Title' /></ViewFields>",
completefunc: function (xData, Status) {
$(xData.responseXML).SPFilterNode("z:row").each(function() {
var liHtml = "<li>" + $(this).attr("ows_Title") + "</li>";
$("#tasksUL").append(liHtml);
});
}
});
});
</script>
<ul id="tasksUL"/>
run configuration -> arguments -> vm arguments
(can also be placed in the debug configuration under Debug Configuration->Arguments->VM Arguments)
- (void)viewDidLoad
{
[super viewDidLoad];
board=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.height, 80)];
board.backgroundColor=[UIColor greenColor];
[self.view addSubview:board];
// Do any additional setup after loading the view.
}
-(void)viewDidLayoutSubviews
{
NSString *str=@"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
index=1;
for (int i=0; i<20; i++)
{
UILabel *lbl=[[UILabel alloc]initWithFrame:CGRectMake(-50, 15, 50, 50)];
lbl.tag=i+1;
lbl.text=[NSString stringWithFormat:@"%c",[str characterAtIndex:arc4random()%str.length]];
lbl.textColor=[UIColor darkGrayColor];
lbl.textAlignment=NSTextAlignmentCenter;
lbl.font=[UIFont systemFontOfSize:40];
lbl.layer.borderWidth=1;
lbl.layer.borderColor=[UIColor blackColor].CGColor;
[board addSubview:lbl];
}
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(CallAnimation) userInfo:nil repeats:YES];
NSLog(@"%d",[board subviews].count);
}
-(void)CallAnimation
{
if (index>20) {
index=1;
}
UIView *aView=[board viewWithTag:index];
[self doAnimation:aView];
index++;
NSLog(@"%d",index);
}
-(void)doAnimation:(UIView*)aView
{
[UIView animateWithDuration:10 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
aView.frame=CGRectMake(self.view.frame.size.height, 15, 50, 50);
}
completion:^(BOOL isDone)
{
if (isDone) {
//do Somthing
aView.frame=CGRectMake(-50, 15, 50, 50);
}
}];
}
Your problem is caused by the lack of markers OpenGraph, as you say it is not possible that you implement for some reason.
For you, the only solution is to use the PHP Facebook API.
When creating the application you will have two key data for your code:
YOUR_APP_ID
YOUR_APP_SECRET
Download the Facebook PHP SDK from here.
You can start with this code for share content from your site:
<?php
// Remember to copy files from the SDK's src/ directory to a
// directory in your application on the server, such as php-sdk/
require_once('php-sdk/facebook.php');
$config = array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
'allowSignedRequest' => false // optional but should be set to false for non-canvas apps
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
?>
<html>
<head></head>
<body>
<?php
if($user_id) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$ret_obj = $facebook->api('/me/feed', 'POST',
array(
'link' => 'www.example.com',
'message' => 'Posting with the PHP SDK!'
));
echo '<pre>Post ID: ' . $ret_obj['id'] . '</pre>';
// Give the user a logout link
echo '<br /><a href="' . $facebook->getLogoutUrl() . '">logout</a>';
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl( array(
'scope' => 'publish_stream'
));
echo 'Please <a href="' . $login_url . '">login.</a>';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
// No user, so print a link for the user to login
// To post to a user's wall, we need publish_stream permission
// We'll use the current URL as the redirect_uri, so we don't
// need to specify it here.
$login_url = $facebook->getLoginUrl( array( 'scope' => 'publish_stream' ) );
echo 'Please <a href="' . $login_url . '">login.</a>';
}
?>
</body>
</html>
You can find more examples in the Facebook Developers site:
Setting alpha
property of a view affects its subviews. If you want just transparent background set view's backgroundColor
proprty to a color that has alpha component smaller than 1.
view.backgroundColor = UIColor.white.withAlphaComponent(0.5)
Putting an answer , as my reputation aint enough to comment. But dont look at this as an answer, just a additional info, as myself, had some problems with both footer, and positioning.
When setting up the page, so that my footer always stays at the bottom, with position absolute, and main container/wrapper with relative position.
I then found some issues with my text content, and a menu inside the same content(white part of page between header and footer), when setting these to absolute, footer no longer stays down.
Postitioning is, as you say a complex theme.
My solution, to the content I wanted in 'absolute' positon in my webpage, and not be pushed to the side, when in example opening a drop down menu, was to actually give it postition relative, and putting it 35em below my drop down menu. (35em is the heigth of my dropdown menu, when fully extended)
Then, Top:-35em, for the content that before was pushed to the side. And then adding margin-bottom:-35em. This way, the content is "below" my drop down menu, but visually it is side by side with my drop down menu! And the white space below down to the footer, is with only 10em margin, as it was before starting to play around with this. So my solution to this was like this :
html, body {
margin:0;
padding:0;
height:100%;
}
h1 {
margin:0;
}
#webpage {
position:relative;
min-height:100%;
margin:0;
overflow:auto;
}
#header {
height:5em;
width:100%;
padding:0;
margin:0;
}
#text {
position:relative;
margin-bottom:-32em;
padding-top:2em;
padding-right:2em;
padding-bottom:10em;
background-repeat:no-repeat;
width:70%;
padding-left:auto;
margin-left:auto;
margin-right:auto;
right:10em;
float:right;
top:-32em;
}
#dropdown {
position:absolute;
left:0;
width:20%;
clear:both;
display:block;
position:relative;
top:1em;
height:35em;
}
#footer {
position:absolute;
width:100%;
right:0;
bottom:0;
height:5em;
margin:0;
margin-top:5em;
}
I see your question is answered good, but after alot of troubleing I found this to be a very good solution, and a way to understand better how positioning works.. When I place my text content, below my drop down menu, it doesn't push my text to the side. If I changed the text to position absolute, the footer did not stay in place. As I can believe this is an issue for more people then me, I add this here. What in fact happends, is I put the text, 35ems, below my drop down.
Then, I visually put it right next to eachother, with relative position, and top:-35em;, and evening out the huge space below, with margin:-35em;
negative values are underestimated at times, very good functionality, when one understands these positions better!
Natually, fixed position, also seemed logic for my footer, but I do really want the footer to go below the viewport, if the text, or content, is longer than the viewport. And to stay at the bottom, if there is little content on the page.
This setupp fixed that very nicely, and remember to use 'em', not 'px' for a more fluid/dynamic page layout! :)
(there may be better solutions, but this works for me cross platforms, as well as devices).
I use the html code tag after each line (see below) and it works for me.
George Benson </br>
123 Main Street </br>
New York, Ny 12344 </br>
I have seen people use it to make sure that a structure takes a whole cache line to prevent false sharing in a multithreaded context. If you are going to have a large number of objects that are going to be loosely packed by default it could save memory and improve cache performance to pack them tighter, though unaligned memory access will usually slow things down so there might be a downside.
For future searchers... The following is a jQuery-ified version of FlySwat's accepted answer:
var labels = $("label");
for (var i = 0; i < labels.length; i++) {
var fieldId = labels[i].htmlFor;
if (fieldId != "") {
var elem = $("#" + fieldId);
if (elem.length != 0) {
elem.data("label", $(labels[i]));
}
}
}
Using:
$("#myFormElemId").data("label").css("border","3px solid red");
All of these methods are great. I have found another simple resource that is a great example of creating a dynamic form using "onchange" with AJAX.
http://www.w3schools.com/php/php_ajax_database.asp
I simply modified the text table output to anther select dropdown populated based on the selection of the first drop down. For my application a user will select a state then the second dropdown will be populated with the cities for the selected state. Much like the JSON example above but with php and mysql.
Though previous posters covered your particular error, you can get 'Undefined reference' linker errors when attempting to compile C code with g++, if you don't tell the compiler to use C linkage.
For example you should do this in your C header files:
extern "C" {
...
void myfunc(int param);
...
}
To make 'myfunc' available in C++ programs.
If you still also want to use this from C, wrap the extern "C" {
and }
in #ifdef __cplusplus
preprocessor conditionals, like
#ifdef __cplusplus
extern "C" {
#endif
This way, the extern
block will just be “skipped” when using a C compiler.
I noticed it myself, and found the files inside the backup folder. You can check where it is using Menu:Settings -> Preferences -> Backup. Note : My NPP installation is portable, and on Windows, so YMMV.
It is at the same location: ~/.android/debug.keystore
Telerik today released a Beta of their own decompilation tool, JustDecompile. Closed source, but free and looks promising.
The for
attribute of the <label>
tag should be equal to the id
attribute of the related element to bind them together.
my $output_file;
if((scalar (@ARGV) == 2) && ($ARGV[0] eq "-i"))
{
$output_file= chomp($ARGV[1]) ;
}
I would prefer std::distance(vec.begin(), it)
as it will allow me to change the container without any code changes. For example, if you decide to use std::list
instead of std::vector
which doesn't provide a random access iterator your code will still compile. Since std::distance picks up the optimal method depending on iterator traits you'll not have any performance degradation either.
You should have a div that just contains the console messages, that is, previous commands and their output. And underneath put an input or textarea that just holds the command you are typing.
-------------------------------
| consle output ... |
| more output |
| prevous commands and data |
-------------------------------
> This is an input box.
That way you just send the value of the input box to the server for processing, and append the result to the console messages div.
Another alternative with data.table.
EXAMPLE DATA
dt1 <- data.table(df1)
dt2 <- data.table(df2)
setkey(dt1,x)
setkey(dt2,x)
CODE
dt2[dt1,list(y=ifelse(is.na(y),0,y))]
Some of the answers here haven't really helped.
People are showing you how to find stuff, but now how to replace it.
I just had a look, and it looks like it's Ctrl+H for replace, then you get the find dialog as well as a replace dialog. This worked for me.
I got it working for me in ReactJS using create-react-app
by putting this in my App.css
:
@-moz-document url-prefix() {
html,
body {
scrollbar-width: none;
}
}
Also, the body
element has overflow: auto
Try width: max-content
to adjust the width of the div by it's content.
<!DOCTYPE html>
<html>
<head>
<style>
div.ex1 {
width:500px;
margin: auto;
border: 3px solid #73AD21;
}
div.ex2 {
width: max-content;
margin: auto;
border: 3px solid #73AD21;
}
</style>
</head>
<body>
<div class="ex1">This div element has width 500px;</div>
<br>
<div class="ex2">Width by content size</div>
</body>
</html>
The reason for the error is that the nextInt only pulls the integer, not the newline. If you add a in.nextLine() before your for loop, it will eat the empty new line and allow you to enter 3 names.
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = in.nextInt();
names = new String[nnames];
in.nextLine();
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}
or just read the line and parse the value as an Integer.
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = Integer.parseInt(in.nextLine().trim());
names = new String[nnames];
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}
wget
wget
is a linux command, not a PHP command, so to run this you woud need to use exec
, which is a PHP command for executing shell commands.
exec("wget --http-user=[user] --http-password=[pass] http://www.example.com/file.xml");
This can be useful if you are downloading a large file - and would like to monitor the progress, however when working with pages in which you are just interested in the content, there are simple functions for doing just that.
The exec
function is enabled by default, but may be disabled in some situations. The configuration options for this reside in your php.ini
, to enable, remove exec
from the disabled_functions
config string.
alternative
Using file_get_contents
we can retrieve the contents of the specified URL/URI. When you just need to read the file into a variable, this would be the perfect function to use as a replacement for curl - follow the URI syntax when building your URL.
// standard url
$content = file_get_contents("http://www.example.com/file.xml");
// or with basic auth
$content = file_get_contents("http://user:[email protected]/file.xml");
As noted by Sean the Bean
- you may also need to change allow_url_fopen
to true
in your php.ini to allow the use of a URL in this method, however, this should be true by default.
If you want to then store that file locally, there is a function file_put_contents
to write that into a file, combined with the previous, this could emulate a file download:
file_put_contents("local_file.xml", $content);
just change it to
compile 'com.google.android.gms:play-services-maps:9.6.0'
compile 'com.google.android.gms:play-services-location:9.6.0'
this works for me current version is 10.0.1
@Kwang-Chun Kang Thanks Kang a lot! I found the solution is working and very helpful, it really save my day. For me I am trying to create a React.js component that convert *.xlsx to json object when user upload the excel file to a html input tag. First I need to install XLSX package with:
npm install xlsx --save
Then in my component code, import with:
import XLSX from 'xlsx'
The component UI should look like this:
<input
accept=".xlsx"
type="file"
onChange={this.fileReader}
/>
It calls a function fileReader(), which is exactly same as the solution provided. To learn more about fileReader API, I found this blog to be helpful: https://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api
If your code should work in both Python 2 and 3, you can achieve this by loading this at the beginning of your program:
from __future__ import print_function # If code has to work in Python 2 and 3!
Then you can print in the Python 3 way:
print("python")
If you want to print something without creating a new line - you can do this:
for number in range(0, 10):
print(number, end=', ')
These may not solve exactly your "real-world problems", but perhaps something useful ...
Our web site includes PhoneGap and jQuery Mobile tutorials for a media player, barcode scanner, google maps, and OAuth.
Also, my github page has code, but no tutorial, for two apps:
If you want to import a specific function or class from a module, you can do this:
import importlib
import sys
importlib.reload(sys.modules['my_module'])
from my_module import my_function
Use function die():
or die(mysql_error());
To do this and avoid the E_STRICT and not mess with the array's internal pointer you can use:
function lelement($array) {return end($array);}
$last_element = lelement($array);
lelement only works with a copy so it doesn't affect the array's pointer.
Disable horizontal scrollbar completely by adding this code.
body{
overflow-x: hidden;
overflow-y: scroll;
}
Delete existing service and create a same new service solved my problems. My problems is that the loading balancing IP I defines is used so that external endpoint is pending. When I changed a new load balancing IP it still couldn't work.
Finally, delete existing service and create a new one solved my problem.
We can run Linux containers on Windows. Docker for Windows uses Hyper-v based Linux-Kit or WSL2 as backend to facilitate Linux containers.
If any Linux distribution having this kind of setup, we can run Windows containers. Docker for Linux supports only Linux containers.
Write the table name in the query editor select the name and press Alt+F1 and it will bring all the information of the table.
You are pretty confused my friend. There are no LOOPS in SQL, only in PL/SQL. Here's a few examples based on existing Oracle table - copy/paste to see results:
-- Numeric FOR loop --
set serveroutput on -->> do not use in TOAD --
DECLARE
k NUMBER:= 0;
BEGIN
FOR i IN 1..10 LOOP
k:= k+1;
dbms_output.put_line(i||' '||k);
END LOOP;
END;
/
-- Cursor FOR loop --
set serveroutput on
DECLARE
CURSOR c1 IS SELECT * FROM scott.emp;
i NUMBER:= 0;
BEGIN
FOR e_rec IN c1 LOOP
i:= i+1;
dbms_output.put_line(i||chr(9)||e_rec.empno||chr(9)||e_rec.ename);
END LOOP;
END;
/
-- SQL example to generate 10 rows --
SELECT 1 + LEVEL-1 idx
FROM dual
CONNECT BY LEVEL <= 10
/
If you use proxy, you will have to edit the Nuget.config file.
In Windows 7 and 10, this file is in the path:
C:\Users\YouUser\AppData\Roaming\NuGet.
Include the setting:
<config>
<add key = "http_proxy" value = "http://Youproxy:8080" />
<add key = "http_proxy.user" value = "YouProxyUser" />
</config>
It seems to me, that for current javascript implementations,
var [result='default']=[possiblyUndefinedValue]
is a nice way to do this (using object deconstruction).
because if you change your code with
def gukan(count):
while count!=100:
print(count)
count=count+3;
gukan(0)
count reaches 99 and then, at the next iteration 102.
So
count != 100
never evaluates true and the loop continues forever
If you want to count up to 100 you may use
def gukan(count):
while count <= 100:
print(count)
count=count+3;
gukan(0)
or (if you want 100 always printed)
def gukan(count):
while count <= 100:
print(count)
count=count+3;
if count > 100:
count = 100
gukan(0)
Simplest solution, if you want to insert (an element or array) after a certain key:
function array_splice_after_key($array, $key, $array_to_insert)
{
$key_pos = array_search($key, array_keys($array));
if($key_pos !== false){
$key_pos++;
$second_array = array_splice($array, $key_pos);
$array = array_merge($array, $array_to_insert, $second_array);
}
return $array;
}
So, if you have:
$array = [
'one' => 1,
'three' => 3
];
$array_to_insert = ['two' => 2];
And execute:
$result_array = array_splice_after_key($array, 'one', $array_to_insert);
You'll have:
Array (
['one'] => 1
['two'] => 2
['three'] => 3
)
You can use the % character to 'escape' characters that aren't allowed in URLs. See [RFC 1738].
A table of ASCII values on http://www.asciitable.com/.
You can see &
is 26 in hexadecimal - so you need M%26M.
Just to extend the answer above you can also index your columns rather than specifying the column names which can also be useful depending on what you're doing. Given that your location is the first field it would look like this:
bar <- foo[foo[ ,1] == "there", ]
This is useful because you can perform operations on your column value, like looping over specific columns (and you can do the same by indexing row numbers too).
This is also useful if you need to perform some operation on more than one column because you can then specify a range of columns:
foo[foo[ ,c(1:N)], ]
Or specific columns, as you would expect.
foo[foo[ ,c(1,5,9)], ]
you can get loccalhost page by writing localhost/xampp
or by writing http://127.0.0.1
you will get the local host page. After starting the apache serve that can be from wamp, xamp or lamp.
Use this code between two words:
& vbCrLf &
Using this, the next word displays on the next line.
I got trouble to get it so I post pictures showing different options:
Very very similar UI since at least Chrome 38.0.2125.111 [11 December 2014]
In tab Sources
:
When button is activated, you can Pause On Caught Exceptions
with the checkbox below:
Chrome 27.0.1453.93 Stable
calculate distance in Mysql
SELECT (6371 * acos(cos(radians(lat2)) * cos(radians(lat1) ) * cos(radians(long1) -radians(long2)) + sin(radians(lat2)) * sin(radians(lat1)))) AS distance
thus distance value will be calculated and anyone can apply as required.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:padding="20dp" > <TextView android:id="@+id/textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:shadowColor="#000" android:shadowDx="0" android:shadowDy="0" android:shadowRadius="50" android:text="Text Shadow Example1" android:textColor="#FBFBFB" android:textSize="28dp" android:textStyle="bold" /> <TextView android:id="@+id/textview2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="Text Shadow Example2" android:textColor="#FBFBFB" android:textSize="28dp" android:textStyle="bold" /> </LinearLayout>
In the above XML layout code, the textview1 is given with Shadow effect in the layout. below are the configuration items are
android:shadowDx – specifies the X-axis offset of shadow. You can give -/+ values, where -Dx draws a shadow on the left of text and +Dx on the right
android:shadowDy – it specifies the Y-axis offset of shadow. -Dy specifies a shadow above the text and +Dy specifies below the text.
android:shadowRadius – specifies how much the shadow should be blurred at the edges. Provide a small value if shadow needs to be prominent. android:shadowColor – specifies the shadow color
Shadow Effect on Android TextView pragmatically
Use below code snippet to get the shadow effect on the second TextView pragmatically.
TextView textv = (TextView) findViewById(R.id.textview2); textv.setShadowLayer(30, 0, 0, Color.RED);
Output :
if you use jQuery, its quite simple. Here you go
$(document).keypress(
function(event){
if (event.which == '13') {
event.preventDefault();
}
});
C - an older programming language that is described as Hands-on. As the programmer you must tell the program to do everything. Also this language will let you do almost anything. It does not support object orriented code. Thus no classes.
C++ - an extention language per se of C. In C code ++ means increment 1. Thus C++ is better than C. It allows for highly controlled object orriented code. Once again a very hands on language that goes into MUCH detail.
C# - Full object orriented code resembling the style of C/C++ code. This is really closer to JAVA. C# is the latest version of the C style languages and is very good for developing web applications.
Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.
As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.
long unixTime = System.currentTimeMillis() / 1000L;
You could use the PEAR Mail classes and methods, which allows you to check for errors via:
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}
You can find an example here.
You probably need more blur and a little less spread.
box-shadow: -10px 0px 10px 1px #aaaaaa;
Try messing around with the box shadow generator here http://css3generator.com/ until you get your desired effect.
To wrap in single quotes (for example) ciw'<C-r>"'<esc>
works, but repeat won't work. Try:
ciw'<C-r><C-o>"'<esc>
This puts the contents of the default register "literally". Now you can press .
on any word to wrap it in quotes. To learn more see :h[elp] i_ctrl-r
and more about text objects at :h text-objects
Source: http://vimcasts.org/episodes/pasting-from-insert-mode/
You can add the AfterViewInit lifecycle hook to your component.
ngAfterViewInit() {
window.scrollTo(0, 0);
}
If your are referring to two worksheets please use this formula
=COUNTIF(Worksheet2!$A$1:$A$50,Worksheet1cellA1)
In case referring to to more than two worksheets please use this formula
=COUNTIF(Worksheet2!$A$1:$A$50,Worksheet1cellA1)+=COUNTIF
(Worksheet3!$A$1:$A$50,Worksheet1cellA1)+=
COUNTIF(Worksheet4!$A$1:$A$50,Worksheet1cellA1)
You can write:
python
import keras
keras.__version__
Try this:
UPDATE data_table t, (SELECT DISTINCT ID, NAME, VALUE
FROM data_table
WHERE VALUE IS NOT NULL AND VALUE != '') t1
SET t.VALUE = t1.VALUE
WHERE t.ID = t1.ID
AND t.NAME = t1.NAME
Swing + SwingX + Miglayout is my combination of choice. Miglayout is so much simpler than Swings perceived 200 different layout managers and much more powerful. Also, it provides you with the ability to "debug" your layouts, which is especially handy when creating complex layouts.
The kind of array definition seems the key: In my case it is a one dimension array of 17 items which have to convert to a two dimension array
Defintion for columns: object[,] Array = new object[17, 1];
Defintion for rows object[,] Array= new object[1,17];
The code for value2 is in both cases the same Excel.Range cell = activeWorksheet.get_Range(Range); cell.Value2 = Array;
LG Georg
I find, if the data is imported, you may need to use the trim command on top of it, to get your details. =LEFT(TRIM(B2),8) In my case, I was using it to find a IP range. 10.3.44.44 with mask 255.255.255.0, so response is: 10.3.44 Kind of handy.
Assuming you only have the list of items and a list of true/required indices, this should be the fastest:
property_asel = [ property_a[index] for index in good_indices ]
This means the property selection will only do as many rounds as there are true/required indices. If you have a lot of property lists that follow the rules of a single tags (true/false) list you can create an indices list using the same list comprehension principles:
good_indices = [ index for index, item in enumerate(good_objects) if item ]
This iterates through each item in good_objects (while remembering its index with enumerate) and returns only the indices where the item is true.
For anyone not getting the list comprehension, here is an English prose version with the code highlighted in bold:
list the index for every group of index, item that exists in an enumeration of good objects, if (where) the item is True
Using CSS only:
Right/Left Flippiing: Working Fiddle
.Container
{
height: 200px;
overflow-x: auto;
}
.Content
{
height: 300px;
}
.Flipped
{
direction: rtl;
}
.Content
{
direction: ltr;
}
Top/Bottom Flipping: Working Fiddle
.Container
{
width: 200px;
overflow-y: auto;
}
.Content
{
width: 300px;
}
.Flipped, .Flipped .Content
{
transform:rotateX(180deg);
-ms-transform:rotateX(180deg); /* IE 9 */
-webkit-transform:rotateX(180deg); /* Safari and Chrome */
}
Here's a function that will dynamically create a CSS rule in all major browsers. createCssRule
takes a selector (e.g. "p.purpleText"), a rule (e.g. "color: purple;") and optionally a Document
(the current document is used by default):
var addRule;
if (typeof document.styleSheets != "undefined" && document.styleSheets) {
addRule = function(selector, rule) {
var styleSheets = document.styleSheets, styleSheet;
if (styleSheets && styleSheets.length) {
styleSheet = styleSheets[styleSheets.length - 1];
if (styleSheet.addRule) {
styleSheet.addRule(selector, rule)
} else if (typeof styleSheet.cssText == "string") {
styleSheet.cssText = selector + " {" + rule + "}";
} else if (styleSheet.insertRule && styleSheet.cssRules) {
styleSheet.insertRule(selector + " {" + rule + "}", styleSheet.cssRules.length);
}
}
}
} else {
addRule = function(selector, rule, el, doc) {
el.appendChild(doc.createTextNode(selector + " {" + rule + "}"));
};
}
function createCssRule(selector, rule, doc) {
doc = doc || document;
var head = doc.getElementsByTagName("head")[0];
if (head && addRule) {
var styleEl = doc.createElement("style");
styleEl.type = "text/css";
styleEl.media = "screen";
head.appendChild(styleEl);
addRule(selector, rule, styleEl, doc);
styleEl = null;
}
};
createCssRule("body", "background-color: purple;");
If you have a dataset named daily_data
:
daily_data<-daily_data[order(as.Date(daily_data$date, format="%d/%m/%Y")),]
I checked all the answers around the web and the best one seemed to be: (actually it isn't)
<img src="image.png?cache=none">
at first.
However, if you add cache=none parameter (which is static "none" word), it doesn't effect anything, browser still loads from cache.
Solution to this problem was:
<img src="image.png?nocache=<?php echo time(); ?>">
where you basically add unix timestamp to make the parameter dynamic and no cache, it worked.
However, my problem was a little different: I was loading on the fly generated php chart image, and controlling the page with $_GET parameters. I wanted the image to be read from cache when the URL GET parameter stays the same, and do not cache when the GET parameters change.
To solve this problem, I needed to hash $_GET but since it is array here is the solution:
$chart_hash = md5(implode('-', $_GET));
echo "<img src='/images/mychart.png?hash=$chart_hash'>";
Edit:
Although the above solution works just fine, sometimes you want to serve the cached version UNTIL the file is changed. (with the above solution, it disables the cache for that image completely) So, to serve cached image from browser UNTIL there is a change in the image file use:
echo "<img src='/images/mychart.png?hash=" . filemtime('mychart.png') . "'>";
filemtime() gets file modification time.
The SpeechRecognition
library requires Python 3.3 or up:
Requirements
[...]
The first software requirement is Python 3.3 or better. This is required to use the library.
and from the Trove classifiers:
Programming Language :: Python
Programming Language :: Python :: 3
Programming Language :: Python :: 3.3
Programming Language :: Python :: 3.4
The urllib.request
module is part of the Python 3 standard library; in Python 2 you'd use urllib2
here.
Look how I format my date $jour in the parameters. It depends if you use a expr()->like or a expr()->lte
$qb
->select('e')
->from('LdbPlanningBundle:EventEntity', 'e')
->where(
$qb->expr()->andX(
$qb->expr()->orX(
$qb->expr()->like('e.start', ':jour1'),
$qb->expr()->like('e.end', ':jour1'),
$qb->expr()->andX(
$qb->expr()->lte('e.start', ':jour2'),
$qb->expr()->gte('e.end', ':jour2')
)
),
$qb->expr()->eq('e.user', ':user')
)
)
->andWhere('e.user = :user ')
->setParameter('user', $user)
->setParameter('jour1', '%'.$jour->format('Y-m-d').'%')
->setParameter('jour2', $jour->format('Y-m-d'))
->getQuery()
->getArrayResult()
;
If you want to pull a particular file from another branch just do
git checkout branch1 -- filenamefoo.txt
This will pull a version of the file from one branch into the current tree
-XX:PermSize
specifies the initial size that will be allocated during startup of the JVM. If necessary, the JVM will allocate up to -XX:MaxPermSize
.
I want to improve on @adf88's answer. I feel that pseudocode for the STDCALL does not reflect the way of how it happens in reality. 'a', 'b', and 'c' aren't popped from the stack in the function body. Instead they are popped by the ret
instruction (ret 12
would be used in this case) that in one swoop jumps back to the caller and at the same time pops 'a', 'b', and 'c' from the stack.
Here is my version corrected according to my understanding:
STDCALL:
/* 1. calling STDCALL in pseudo-assembler (similar to what the compiler outputs) */
push on the stack a copy of 'z', then copy of 'y', then copy of 'x'
call
move contents of register A to 'i' variable
/* 2. STDCALL 'Function' body in pseaudo-assembler */
copy 'a' (from stack) to register A
copy 'b' (from stack) to register B
add A and B, store result in A
copy 'c' (from stack) to register B
add A and B, store result in A
jump back to caller code and at the same time pop 'a', 'b' and 'c' off the stack (a, b and
c are removed from the stack in this step, result in register A)
Late, but relevant to request and hopefully helpful. If using an external service (as suggested in the reply by CommonsWare) then Docmosis has a cloud service that might help - offloading processing to a cloud service that does the heavy processing. That approach is ideal in some circumstances but of course relies on being net-connected.
I think you are looking for std::any_of
, which will return a true/false answer to detect if an element is in a container (array, vector, deque, etc.)
int val = SOME_VALUE; // this is the value you are searching for
bool exists = std::any_of(std::begin(myArray), std::end(myArray), [&](int i)
{
return i == val;
});
If you want to know where the element is, std::find
will return an iterator to the first element matching whatever criteria you provide (or a predicate you give it).
int val = SOME_VALUE;
int* pVal = std::find(std::begin(myArray), std::end(myArray), val);
if (pVal == std::end(myArray))
{
// not found
}
else
{
// found
}
If you happen to use Vavr(formerly known as Javaslang), this can be as easy as:
Iterable i = //...
Stream.ofAll(i);
See here for starting the service and here for how to make it permanent. In short to test it, open a "DOS" terminal with administrator privileges and write:
shell> "C:\Program Files\MySQL\[YOUR MYSQL VERSION PATH]\bin\mysqld"
The shortest answer is
Please try this.
<switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/shop" component={Shop} />
</switch>
The problem with solutions based on sums of numbers is they don't take into account the cost of storing and working with numbers with large exponents... in practice, for it to work for very large n, a big numbers library would be used. We can analyse the space utilisation for these algorithms.
We can analyse the time and space complexity of sdcvvc and Dimitris Andreou's algorithms.
Storage:
l_j = ceil (log_2 (sum_{i=1}^n i^j))
l_j > log_2 n^j (assuming n >= 0, k >= 0)
l_j > j log_2 n \in \Omega(j log n)
l_j < log_2 ((sum_{i=1}^n i)^j) + 1
l_j < j log_2 (n) + j log_2 (n + 1) - j log_2 (2) + 1
l_j < j log_2 n + j + c \in O(j log n)`
So l_j \in \Theta(j log n)
Total storage used: \sum_{j=1}^k l_j \in \Theta(k^2 log n)
Space used: assuming that computing a^j
takes ceil(log_2 j)
time, total time:
t = k ceil(\sum_i=1^n log_2 (i)) = k ceil(log_2 (\prod_i=1^n (i)))
t > k log_2 (n^n + O(n^(n-1)))
t > k log_2 (n^n) = kn log_2 (n) \in \Omega(kn log n)
t < k log_2 (\prod_i=1^n i^i) + 1
t < kn log_2 (n) + 1 \in O(kn log n)
Total time used: \Theta(kn log n)
If this time and space is satisfactory, you can use a simple recursive algorithm. Let b!i be the ith entry in the bag, n the number of numbers before removals, and k the number of removals. In Haskell syntax...
let
-- O(1)
isInRange low high v = (v >= low) && (v <= high)
-- O(n - k)
countInRange low high = sum $ map (fromEnum . isInRange low high . (!)b) [1..(n-k)]
findMissing l low high krange
-- O(1) if there is nothing to find.
| krange=0 = l
-- O(1) if there is only one possibility.
| low=high = low:l
-- Otherwise total of O(knlog(n)) time
| otherwise =
let
mid = (low + high) `div` 2
klow = countInRange low mid
khigh = krange - klow
in
findMissing (findMissing low mid klow) (mid + 1) high khigh
in
findMising 1 (n - k) k
Storage used: O(k)
for list, O(log(n))
for stack: O(k + log(n))
This algorithm is more intuitive, has the same time complexity, and uses less space.
Take advantage of SORT and LIMIT as you would with pagination. If you want the ith block of rows, use OFFSET.
SELECT val FROM big_table
where val = someval
ORDER BY id DESC
LIMIT n;
In response to Nir: The sort operation is not necessarily penalized, this depends on what the query planner does. Since this use case is crucial for pagination performance, there are some optimizations (see link above). This is true in postgres as well "ORDER BY ... LIMIT can be done without sorting " E.7.1. Last bullet
explain extended select id from items where val = 48 order by id desc limit 10;
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
| 1 | SIMPLE | items | const | PRIMARY | PRIMARY | 4 | const | 1 | Using index |
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
Kafka is a distributed system and needs Zookeeper. you have to start zookeeper too. Follow "Quick Start" here : https://kafka.apache.org/0100/documentation.html#quickstart
Ctrl+Shift+Space shows the Edit.ParameterInfo
for the selected method, and by selected method I mean the caret must be within the method parentheses.
Here is the Visual Studio 2010 Keybinding Poster.
And for those still using 2008.
A small note on try
/finally
: The finally will always execute unless
System.exit()
is called.try{}
block never ends (e.g. endless loop).Additionally, this will only work if Value is of type bool. Normally this is used with predicates. Any predicate would be generally used find whether there is any element satisfying a given condition. Here you're just doing a map from your element i to a bool property. It will search for an "i" whose Value property is true. Once done, the method will return true.
Whilst this an old question, I ran into this problem myself recently and some of the answers here are now deprecated (as the comments point out). So for the benefit of others who may have stumbled here:
A term
query can be used to find the exact term specified in the reverse index:
{
"query": {
"term" : { "tags" : "a" }
}
From the documenation https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-term-query.html
Alternatively you can use a terms
query, which will match all documents with any of the items specified in the given array:
{
"query": {
"terms" : { "tags" : ["a", "c"]}
}
https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-terms-query.html
One gotcha to be aware of (which caught me out) - how you define the document also makes a difference. If the field you're searching in has been indexed as a text
type then Elasticsearch will perform a full text search (i.e using an analyzed
string).
If you've indexed the field as a keyword
then a keyword search using a 'non-analyzed' string is performed. This can have a massive practical impact as Analyzed strings are pre-processed (lowercased, punctuation dropped etc.) See (https://www.elastic.co/guide/en/elasticsearch/guide/master/term-vs-full-text.html)
To avoid these issues, the string field has split into two new types: text, which should be used for full-text search, and keyword, which should be used for keyword search. (https://www.elastic.co/blog/strings-are-dead-long-live-strings)
Very simple:
function myfunction($products, $field, $value)
{
foreach($products as $key => $product)
{
if ( $product[$field] === $value )
return $key;
}
return false;
}
Starting with PHP 7.3.0 it's possible to do without resetting the internal pointer. You would use array_key_first
. If you're sure that your array has values it in then you can just do:
$first = $array[array_key_first($array)];
More likely, you'll want to handle the case where the array is empty:
$first = (empty($array)) ? $default : $array[array_key_first($array)];
To get the native reference to something like an ion-input
, ry using this
@ViewChild('fileInput', { read: ElementRef }) fileInput: ElementRef;
and then
this.fileInput.nativeElement.querySelector('input').click()
Implemented the same in scala, Please help urself with converting to Java, the core logic and functions used stays the same.
import java.text.SimpleDateFormat
import org.apache.commons.lang.time.DateUtils
object MultiDataFormat {
def main(args: Array[String]) {
val dates =Array("2015-10-31","26/12/2015","19-10-2016")
val possibleDateFormats:Array[String] = Array("yyyy-MM-dd","dd/MM/yyyy","dd-MM-yyyy")
val sdf = new SimpleDateFormat("yyyy-MM-dd") //change it as per the requirement
for (date<-dates) {
val outputDate = DateUtils.parseDateStrictly(date, possibleDateFormats)
System.out.println("inputDate ==> " + date + ", outputDate ==> " +outputDate + " " + sdf.format(outputDate) )
}
}
}
This can simply also mean you are missing or have too many parentheses. For example this has too many, and will result in unexpected EOF
:
print(9, not (a==7 and b==6)
You should use the background attribute to give an image to that element, and I would use ::after instead of before, this way it should be already drawn on top of your element.
.Modal:before{
content: '';
background:url('blackCarrot.png');
width: /* width of the image */;
height: /* height of the image */;
display: block;
}
I had similar problem (in bash terminal command was working correctly but zsh showed command not found error)
just paste whatever you were earlier pasting in ~/.bashrc to:
~/.zshrc
Disabled elements don't fire mouse events. Most browsers will propagate an event originating from the disabled element up the DOM tree, so event handlers could be placed on container elements. However, Firefox doesn't exhibit this behaviour, it just does nothing at all when you click on a disabled element.
I can't think of a better solution but, for complete cross browser compatibility, you could place an element in front of the disabled input and catch the click on that element. Here's an example of what I mean:
<div style="display:inline-block; position:relative;">
<input type="text" disabled />
<div style="position:absolute; left:0; right:0; top:0; bottom:0;"></div>
</div>?
jq:
$("div > div").click(function (evt) {
$(this).hide().prev("input[disabled]").prop("disabled", false).focus();
});?
Example: http://jsfiddle.net/RXqAm/170/ (updated to use jQuery 1.7 with prop
instead of attr
).
My issue was that I was using 'React.PureComponent' when I should have been using 'React.Component'.
You can add an image resource in the project then (right click on the project and choose the Properties item) access that in this way:
this.picturebox.image = projectname.properties.resources.imagename;
If you would like to do your filtering in LINQ, you can do it like this:
var ext = new List<string> { "jpg", "gif", "png" };
var myFiles = Directory
.EnumerateFiles(dir, "*.*", SearchOption.AllDirectories)
.Where(s => ext.Contains(Path.GetExtension(s).TrimStart(".").ToLowerInvariant()));
Now ext
contains a list of allowed extensions; you can add or remove items from it as necessary for flexible filtering.
I think troelskn is close. I would do this instead:
class ClassToTest
{
protected function testThisMethod()
{
// Implement stuff here
}
}
Then, implement something like this:
class TestClassToTest extends ClassToTest
{
public function testThisMethod()
{
return parent::testThisMethod();
}
}
You then run your tests against TestClassToTest.
It should be possible to automatically generate such extension classes by parsing the code. I wouldn't be surprised if PHPUnit already offers such a mechanism (though I haven't checked).
Because the normal mathematical notion of "remainder" is only applicable to integer division. i.e. division that is required to generate integer quotient.
In order to extend the concept of "remainder" to real numbers you have to introduce a new kind of "hybrid" operation that would generate integer quotient for real operands. Core C language does not support such operation, but it is provided as a standard library fmod
function, as well as remainder
function in C99. (Note that these functions are not the same and have some peculiarities. In particular, they do not follow the rounding rules of integer division.)
sleep()causes the thread to definitely stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle (and probably enter a power saving mode). yield()basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should. Otherwise, the current thread will continue to run.
Try using the @
symbol before the url string. Import your css in the following manner:
import Vue from 'vue'
require('@/assets/styles/main.css')
In your App.vue file you can do this to import a css file in the style tag
<template>
<div>
</div>
</template>
<style scoped src="@/assets/styles/mystyles.css">
</style>
I need to copy folder recursively, after trying different solutions, finally end up by ProcessBuilder + expect/spawn
scpFile("192.168.1.1", "root","password","/tmp/1","/tmp");
public void scpFile(String host, String username, String password, String src, String dest) throws Exception {
String[] scpCmd = new String[]{"expect", "-c", String.format("spawn scp -r %s %s@%s:%s\n", src, username, host, dest) +
"expect \"?assword:\"\n" +
String.format("send \"%s\\r\"\n", password) +
"expect eof"};
ProcessBuilder pb = new ProcessBuilder(scpCmd);
System.out.println("Run shell command: " + Arrays.toString(scpCmd));
Process process = pb.start();
int errCode = process.waitFor();
System.out.println("Echo command executed, any errors? " + (errCode == 0 ? "No" : "Yes"));
System.out.println("Echo Output:\n" + output(process.getInputStream()));
if(errCode != 0) throw new Exception();
}
I think using the option default=argparse.SUPPRESS
makes most sense. Then, instead of checking if the argument is not None
, one checks if the argument is in
the resulting namespace.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--foo", default=argparse.SUPPRESS)
ns = parser.parse_args()
print("Parsed arguments: {}".format(ns))
print("foo in namespace?: {}".format("foo" in ns))
$ python argparse_test.py --foo 1
Parsed arguments: Namespace(foo='1')
foo in namespace?: True
Argument is not supplied:
$ python argparse_test.py
Parsed arguments: Namespace()
foo in namespace?: False
execute the command
declare @sql varchar (100)
set @sql ='select * from #td1'
if (@IsMonday+@IsTuesday !='')
begin
set @sql= @sql+' where PickupDay in ('''+@IsMonday+''','''+@IsTuesday+''' )'
end
exec( @sql)
If you trying to get worked hours with some accuracy, try this (tested in SQL Server 2016)
SELECT DATEDIFF(MINUTE,job_start, job_end)/60.00;
Various DATEDIFF functionalities are:
SELECT DATEDIFF(year, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(quarter, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(month, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(dayofyear, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(day, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(week, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(hour, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(minute, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(second, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(millisecond, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
Ref: https://docs.microsoft.com/en-us/sql/t-sql/functions/datediff-transact-sql?view=sql-server-2017
Since it seems impossible to do just with symbol versioning hacks, let's go one step further and compile glibc ourselves.
This setup might work and is quick as it does not recompile the whole GCC toolchain, just glibc.
But it is not reliable as it uses host C runtime objects such as crt1.o
, crti.o
, and crtn.o
provided by glibc. This is mentioned at: https://sourceware.org/glibc/wiki/Testing/Builds?action=recall&rev=21#Compile_against_glibc_in_an_installed_location Those objects do early setup that glibc relies on, so I wouldn't be surprised if things crashed in wonderful and awesomely subtle ways.
For a more reliable setup, see Setup 2 below.
Build glibc and install locally:
export glibc_install="$(pwd)/glibc/build/install"
git clone git://sourceware.org/git/glibc.git
cd glibc
git checkout glibc-2.28
mkdir build
cd build
../configure --prefix "$glibc_install"
make -j `nproc`
make install -j `nproc`
test_glibc.c
#define _GNU_SOURCE
#include <assert.h>
#include <gnu/libc-version.h>
#include <stdatomic.h>
#include <stdio.h>
#include <threads.h>
atomic_int acnt;
int cnt;
int f(void* thr_data) {
for(int n = 0; n < 1000; ++n) {
++cnt;
++acnt;
}
return 0;
}
int main(int argc, char **argv) {
/* Basic library version check. */
printf("gnu_get_libc_version() = %s\n", gnu_get_libc_version());
/* Exercise thrd_create from -pthread,
* which is not present in glibc 2.27 in Ubuntu 18.04.
* https://stackoverflow.com/questions/56810/how-do-i-start-threads-in-plain-c/52453291#52453291 */
thrd_t thr[10];
for(int n = 0; n < 10; ++n)
thrd_create(&thr[n], f, NULL);
for(int n = 0; n < 10; ++n)
thrd_join(thr[n], NULL);
printf("The atomic counter is %u\n", acnt);
printf("The non-atomic counter is %u\n", cnt);
}
Compile and run with test_glibc.sh
:
#!/usr/bin/env bash
set -eux
gcc \
-L "${glibc_install}/lib" \
-I "${glibc_install}/include" \
-Wl,--rpath="${glibc_install}/lib" \
-Wl,--dynamic-linker="${glibc_install}/lib/ld-linux-x86-64.so.2" \
-std=c11 \
-o test_glibc.out \
-v \
test_glibc.c \
-pthread \
;
ldd ./test_glibc.out
./test_glibc.out
The program outputs the expected:
gnu_get_libc_version() = 2.28
The atomic counter is 10000
The non-atomic counter is 8674
Command adapted from https://sourceware.org/glibc/wiki/Testing/Builds?action=recall&rev=21#Compile_against_glibc_in_an_installed_location but --sysroot
made it fail with:
cannot find /home/ciro/glibc/build/install/lib/libc.so.6 inside /home/ciro/glibc/build/install
so I removed it.
ldd
output confirms that the ldd
and libraries that we've just built are actually being used as expected:
+ ldd test_glibc.out
linux-vdso.so.1 (0x00007ffe4bfd3000)
libpthread.so.0 => /home/ciro/glibc/build/install/lib/libpthread.so.0 (0x00007fc12ed92000)
libc.so.6 => /home/ciro/glibc/build/install/lib/libc.so.6 (0x00007fc12e9dc000)
/home/ciro/glibc/build/install/lib/ld-linux-x86-64.so.2 => /lib64/ld-linux-x86-64.so.2 (0x00007fc12f1b3000)
The gcc
compilation debug output shows that my host runtime objects were used, which is bad as mentioned previously, but I don't know how to work around it, e.g. it contains:
COLLECT_GCC_OPTIONS=/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crt1.o
Now let's modify glibc with:
diff --git a/nptl/thrd_create.c b/nptl/thrd_create.c
index 113ba0d93e..b00f088abb 100644
--- a/nptl/thrd_create.c
+++ b/nptl/thrd_create.c
@@ -16,11 +16,14 @@
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
+#include <stdio.h>
+
#include "thrd_priv.h"
int
thrd_create (thrd_t *thr, thrd_start_t func, void *arg)
{
+ puts("hacked");
_Static_assert (sizeof (thr) == sizeof (pthread_t),
"sizeof (thr) != sizeof (pthread_t)");
Then recompile and re-install glibc, and recompile and re-run our program:
cd glibc/build
make -j `nproc`
make -j `nproc` install
./test_glibc.sh
and we see hacked
printed a few times as expected.
This further confirms that we actually used the glibc that we compiled and not the host one.
Tested on Ubuntu 18.04.
This is an alternative to setup 1, and it is the most correct setup I've achieved far: everything is correct as far as I can observe, including the C runtime objects such as crt1.o
, crti.o
, and crtn.o
.
In this setup, we will compile a full dedicated GCC toolchain that uses the glibc that we want.
The only downside to this method is that the build will take longer. But I wouldn't risk a production setup with anything less.
crosstool-NG is a set of scripts that downloads and compiles everything from source for us, including GCC, glibc and binutils.
Yes the GCC build system is so bad that we need a separate project for that.
This setup is only not perfect because crosstool-NG does not support building the executables without extra -Wl
flags, which feels weird since we've built GCC itself. But everything seems to work, so this is only an inconvenience.
Get crosstool-NG and configure it:
git clone https://github.com/crosstool-ng/crosstool-ng
cd crosstool-ng
git checkout a6580b8e8b55345a5a342b5bd96e42c83e640ac5
export CT_PREFIX="$(pwd)/.build/install"
export PATH="/usr/lib/ccache:${PATH}"
./bootstrap
./configure --enable-local
make -j `nproc`
./ct-ng x86_64-unknown-linux-gnu
./ct-ng menuconfig
The only mandatory option that I can see, is making it match your host kernel version to use the correct kernel headers. Find your host kernel version with:
uname -a
which shows me:
4.15.0-34-generic
so in menuconfig
I do:
Operating System
Version of linux
so I select:
4.14.71
which is the first equal or older version. It has to be older since the kernel is backwards compatible.
Now you can build with:
env -u LD_LIBRARY_PATH time ./ct-ng build CT_JOBS=`nproc`
and now wait for about thirty minutes to two hours for compilation.
The .config
that we generated with ./ct-ng x86_64-unknown-linux-gnu
has:
CT_GLIBC_V_2_27=y
To change that, in menuconfig
do:
C-library
Version of glibc
save the .config
, and continue with the build.
Or, if you want to use your own glibc source, e.g. to use glibc from the latest git, proceed like this:
Paths and misc options
Try features marked as EXPERIMENTAL
: set to trueC-library
Source of glibc
Custom location
: say yesCustom location
Custom source location
: point to a directory containing your glibc sourcewhere glibc was cloned as:
git clone git://sourceware.org/git/glibc.git
cd glibc
git checkout glibc-2.28
Once you have built he toolchain that you want, test it out with:
#!/usr/bin/env bash
set -eux
install_dir="${CT_PREFIX}/x86_64-unknown-linux-gnu"
PATH="${PATH}:${install_dir}/bin" \
x86_64-unknown-linux-gnu-gcc \
-Wl,--dynamic-linker="${install_dir}/x86_64-unknown-linux-gnu/sysroot/lib/ld-linux-x86-64.so.2" \
-Wl,--rpath="${install_dir}/x86_64-unknown-linux-gnu/sysroot/lib" \
-v \
-o test_glibc.out \
test_glibc.c \
-pthread \
;
ldd test_glibc.out
./test_glibc.out
Everything seems to work as in Setup 1, except that now the correct runtime objects were used:
COLLECT_GCC_OPTIONS=/home/ciro/crosstool-ng/.build/install/x86_64-unknown-linux-gnu/bin/../x86_64-unknown-linux-gnu/sysroot/usr/lib/../lib64/crt1.o
It does not seem possible with crosstool-NG, as explained below.
If you just re-build;
env -u LD_LIBRARY_PATH time ./ct-ng build CT_JOBS=`nproc`
then your changes to the custom glibc source location are taken into account, but it builds everything from scratch, making it unusable for iterative development.
If we do:
./ct-ng list-steps
it gives a nice overview of the build steps:
Available build steps, in order:
- companion_tools_for_build
- companion_libs_for_build
- binutils_for_build
- companion_tools_for_host
- companion_libs_for_host
- binutils_for_host
- cc_core_pass_1
- kernel_headers
- libc_start_files
- cc_core_pass_2
- libc
- cc_for_build
- cc_for_host
- libc_post_cc
- companion_libs_for_target
- binutils_for_target
- debug
- test_suite
- finish
Use "<step>" as action to execute only that step.
Use "+<step>" as action to execute up to that step.
Use "<step>+" as action to execute from that step onward.
therefore, we see that there are glibc steps intertwined with several GCC steps, most notably libc_start_files
comes before cc_core_pass_2
, which is likely the most expensive step together with cc_core_pass_1
.
In order to build just one step, you must first set the "Save intermediate steps" in .config
option for the intial build:
Paths and misc options
Debug crosstool-NG
Save intermediate steps
and then you can try:
env -u LD_LIBRARY_PATH time ./ct-ng libc+ -j`nproc`
but unfortunately, the +
required as mentioned at: https://github.com/crosstool-ng/crosstool-ng/issues/1033#issuecomment-424877536
Note however that restarting at an intermediate step resets the installation directory to the state it had during that step. I.e., you will have a rebuilt libc - but no final compiler built with this libc (and hence, no compiler libraries like libstdc++ either).
and basically still makes the rebuild too slow to be feasible for development, and I don't see how to overcome this without patching crosstool-NG.
Furthermore, starting from the libc
step didn't seem to copy over the source again from Custom source location
, further making this method unusable.
A bonus if you're also interested in the C++ standard library: How to edit and re-build the GCC libstdc++ C++ standard library source?
Strings are immutable. string.replace
(python 2.x) or str.replace
(python 3.x) creates a new string. This is stated in the documentation:
Return a copy of string s with all occurrences of substring old replaced by new. ...
This means you have to re-allocate the set or re-populate it (re-allocating is easier with set comprehension):
new_set = {x.replace('.good', '').replace('.bad', '') for x in set1}
First, HTML and PDF are not related although they were created around the same time. HTML is intended to convey higher level information such as paragraphs and tables. Although there are methods to control it, it is ultimately up to the browser to draw these higher level concepts. PDF is intended to convey documents and the documents must "look" the same wherever they are rendered.
In an HTML document you might have a paragraph that's 100% wide and depending on the width of your monitor it might take 2 lines or 10 lines and when you print it it might be 7 lines and when you look at it on your phone it might take 20 lines. A PDF file, however, must be independent of the rendering device, so regardless of your screen size it must always render exactly the same.
Because of the musts above, PDF doesn't support abstract things like "tables" or "paragraphs". There are three basic things that PDF supports: text, lines/shapes and images. (There are other things like annotations and movies but I'm trying to keep it simple here.) In a PDF you don't say "here's a paragraph, browser do your thing!". Instead you say, "draw this text at this exact X,Y location using this exact font and don't worry, I've previously calculated the width of the text so I know it will all fit on this line". You also don't say "here's a table" but instead you say "draw this text at this exact location and then draw a rectangle at this other exact location that I've previously calculated so I know it will appear to be around the text".
Second, iText and iTextSharp parse HTML and CSS. That's it. ASP.Net, MVC, Razor, Struts, Spring, etc, are all HTML frameworks but iText/iTextSharp is 100% unaware of them. Same with DataGridViews, Repeaters, Templates, Views, etc. which are all framework-specific abstractions. It is your responsibility to get the HTML from your choice of framework, iText won't help you. If you get an exception saying The document has no pages
or you think that "iText isn't parsing my HTML" it is almost definite that you don't actually have HTML, you only think you do.
Third, the built-in class that's been around for years is the HTMLWorker
however this has been replaced with XMLWorker
(Java / .Net). Zero work is being done on HTMLWorker
which doesn't support CSS files and has only limited support for the most basic CSS properties and actually breaks on certain tags. If you do not see the HTML attribute or CSS property and value in this file then it probably isn't supported by HTMLWorker
. XMLWorker
can be more complicated sometimes but those complications also make it more extensible.
Below is C# code that shows how to parse HTML tags into iText abstractions that get automatically added to the document that you are working on. C# and Java are very similar so it should be relatively easy to convert this. Example #1 uses the built-in HTMLWorker
to parse the HTML string. Since only inline styles are supported the class="headline"
gets ignored but everything else should actually work. Example #2 is the same as the first except it uses XMLWorker
instead. Example #3 also parses the simple CSS example.
//Create a byte array that will eventually hold our final PDF
Byte[] bytes;
//Boilerplate iTextSharp setup here
//Create a stream that we can write to, in this case a MemoryStream
using (var ms = new MemoryStream()) {
//Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
using (var doc = new Document()) {
//Create a writer that's bound to our PDF abstraction and our stream
using (var writer = PdfWriter.GetInstance(doc, ms)) {
//Open the document for writing
doc.Open();
//Our sample HTML and CSS
var example_html = @"<p>This <em>is </em><span class=""headline"" style=""text-decoration: underline;"">some</span> <strong>sample <em> text</em></strong><span style=""color: red;"">!!!</span></p>";
var example_css = @".headline{font-size:200%}";
/**************************************************
* Example #1 *
* *
* Use the built-in HTMLWorker to parse the HTML. *
* Only inline CSS is supported. *
* ************************************************/
//Create a new HTMLWorker bound to our document
using (var htmlWorker = new iTextSharp.text.html.simpleparser.HTMLWorker(doc)) {
//HTMLWorker doesn't read a string directly but instead needs a TextReader (which StringReader subclasses)
using (var sr = new StringReader(example_html)) {
//Parse the HTML
htmlWorker.Parse(sr);
}
}
/**************************************************
* Example #2 *
* *
* Use the XMLWorker to parse the HTML. *
* Only inline CSS and absolutely linked *
* CSS is supported *
* ************************************************/
//XMLWorker also reads from a TextReader and not directly from a string
using (var srHtml = new StringReader(example_html)) {
//Parse the HTML
iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
}
/**************************************************
* Example #3 *
* *
* Use the XMLWorker to parse HTML and CSS *
* ************************************************/
//In order to read CSS as a string we need to switch to a different constructor
//that takes Streams instead of TextReaders.
//Below we convert the strings into UTF8 byte array and wrap those in MemoryStreams
using (var msCss = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_css))) {
using (var msHtml = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_html))) {
//Parse the HTML
iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msHtml, msCss);
}
}
doc.Close();
}
}
//After all of the PDF "stuff" above is done and closed but **before** we
//close the MemoryStream, grab all of the active bytes from the stream
bytes = ms.ToArray();
}
//Now we just need to do something with those bytes.
//Here I'm writing them to disk but if you were in ASP.Net you might Response.BinaryWrite() them.
//You could also write the bytes to a database in a varbinary() column (but please don't) or you
//could pass them to another function for further PDF processing.
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");
System.IO.File.WriteAllBytes(testFile, bytes);
There are good news for HTML-to-PDF demands. As this answer showed, the W3C standard css-break-3 will solve the problem... It is a Candidate Recommendation with plan to turn into definitive Recommendation this year, after tests.
As not-so-standard there are solutions, with plugins for C#, as showed by print-css.rocks.
The to_char()
function is there to format numbers:
select to_char(column_1, 'fm000') as column_2
from some_table;
The fm
prefix ("fill mode") avoids leading spaces in the resulting varchar. The 000
simply defines the number of digits you want to have.
psql (9.3.5) Type "help" for help. postgres=> with sample_numbers (nr) as ( postgres(> values (1),(11),(100) postgres(> ) postgres-> select to_char(nr, 'fm000') postgres-> from sample_numbers; to_char --------- 001 011 100 (3 rows) postgres=>
For more details on the format picture, please see the manual:
http://www.postgresql.org/docs/current/static/functions-formatting.html
plot(t)
is in this case the same as
plot(t[[1]], t[[2]])
As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1
:
> length(t)
[1] 4
> length(1)
[1] 1
In your second example you plot a list with elements named x
and y
, both vectors of length 2,
so plot
plots these two vectors.
Edit:
If you want to plot lines use
plot(t, type="l")
Short answer: When I send files between devices with OBEX I am almost never prompted to pair, so it is certainly possible.
1) An application and the device itself can each be set to need/not-need authentication modes, so often there was no requirement for pairing. For instance most OBEX (OPP) servers don't need any authentication at all so there is not need for pairing/bonding.
Presumably "Wireless Designs"'s answer was covering that case.
2) Then if pairing was required by the device/app:
2.1) Prior to v2.1 for pairing then the two devices needed to have matching passphrase/PINs. So this either needed user involvement (to enter the PINs) or knowledge in the softwareto know the PIN: either defined in the app if pin callback send pin="1234"
, or smarts in the OS like BlueZ and Win7 (see Slide 20 at my Bluetooth in Windows 7 doc) which has logic like: if(remotedevice=headset) then expectedPin ="0000"
. Don't know what Android does
2.2) In v2.1 Secure Simple Pairing (SSP) was added. Which changes pairing to:
if (either is pre-v2.1) then Legacy else if (Out-Of-Band channel) then OutOfBand else if (neither have "Man-in-the-Middle Protection Required") then (i.e. both have "Man-in-the-Middle Protection _Not_ Required") Just-Works else Depending on the two devices' "IO Capabilities", either NumericComparison or Passkey. Passkey is used when one device has KeyboardOnly -- and the peer device _isn't_ NoInputNoOutput. endif
From 32feet.NET's BluetoothWin32Authentication user guide, see also the SSP sections in [1]
So to have pairing be unprompted needs either "JustWorks" or "Out-of-Band" eg your NFC suggestion.
Hope that helps...
if you found out that the memory settings were not being used and in order to change the memory settings, I used the tomcat7w or tomcat8w in the \bin folder.Then the following should pop up:
Click the Java tab and add the arguments.restart tomcat
I would sugest to init the Class from RSC:
import Foundation
import UIKit
// Don't forget the delegate!
class ViewController: UIViewController, UITextFieldDelegate {
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@IBOutlet var myTextField : UITextField?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.myTextField.delegate = self;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
self.view.endEditing(true);
return false;
}
}
Make sure their GroupName
properties are set to the same name:
<asp:RadioButton GroupName="MeasurementSystem" runat="server" Text="US" />
<asp:RadioButton GroupName="MeasurementSystem" runat="server" Text="Metric" />
if you wrote: -Xms512m -Xmx512m when it start, java allocate in those moment 512m of ram for his process and cant increment.
-Xms64m -Xmx512m when it start, java allocate only 64m of ram for his process, but java can be increment his memory occupation while 512m.
I think that second thing is better because you give to java the automatic memory management.
According to http://www.techotopia.com/index.php/Ruby_String_Concatenation_and_Comparison
Doing either
mystring == yourstring
or
mystring.eql? yourstring
Are equivalent.
Use cli utility keytool from java software distribution for import (and trust!) needed certificates
Sample:
From cli change dir to jre\bin
Check keystore (file found in jre\bin directory)
keytool -list -keystore ..\lib\security\cacerts
Enter keystore password: changeit
Download and save all certificates chain from needed server.
Add certificates (before need to remove "read-only" attribute on file "..\lib\security\cacerts") keytool -alias REPLACE_TO_ANY_UNIQ_NAME -import -keystore ..\lib\security\cacerts -file "r:\root.crt"
accidentally I found such a simple tip. Other solutions require the use of InstallCert.Java and JDK
source: http://www.java-samples.com/showtutorial.php?tutorialid=210
The below method can count the number of 1s in negative numbers as well.
private static int countBits(int number) {
int result = 0;
while(number != 0) {
result += number & 1;
number = number >>> 1;
}
return result;
}
However, a number like -1 is represented in binary as 11111111111111111111111111111111 and so will require a lot of shifting. If you don't want to do so many shifts for small negative numbers, another way could be as follows:
private static int countBits(int number) {
boolean negFlag = false;
if(number < 0) {
negFlag = true;
number = ~number;
}
int result = 0;
while(number != 0) {
result += number & 1;
number = number >> 1;
}
return negFlag? (32-result): result;
}
There is a neat way of doing this.
If it's an Unit Test you can do this:
@RunWith(MockitoJUnitRunner.class)
public class MyUnitTest {
@Mock
private MyFirstMock myFirstMock;
@Mock
private MySecondMock mySecondMock;
@Spy
private MySpiedClass mySpiedClass = new MySpiedClass();
// It's gonna inject the 2 mocks and the spied object per reflection to this object
// The java doc of @InjectMocks explains it really well how and when it does the injection
@InjectMocks
private MyClassToTest myClassToTest;
@Test
public void testSomething() {
}
}
EDIT: If it's an Integration test you can do this(not intended to be used that way with Spring. Just showcase that you can initialize mocks with diferent Runners):
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("aplicationContext.xml")
public class MyIntegrationTest {
@Mock
private MyFirstMock myFirstMock;
@Mock
private MySecondMock mySecondMock;
@Spy
private MySpiedClass mySpiedClass = new MySpiedClass();
// It's gonna inject the 2 mocks and the spied object per reflection to this object
// The java doc of @InjectMocks explains it really well how and when it does the injection
@InjectMocks
private MyClassToTest myClassToTest;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testSomething() {
}
}
mysql> SHOW ENGINE INNODB STATUS;
But in my case only this way could help:
1. Make backup of current DB
2. Drop DB (not all tables, but DB)
3. Create DB (check that you still have previleges)
4. Restore DB from backup
In my understanding, calling Dispose()
is necessary only when it's locking resources you need later (like a particular connection). It's always recommended to free resources you're no longer using, even if you don't need them again, simply because you shouldn't generally be holding onto resources you're not using (pun intended).
The Microsoft example is not incorrect, necessarily. All resources used will be released when the application exits. And in the case of that example, that happens almost immediately after the HttpClient
is done being used. In like cases, explicitly calling Dispose()
is somewhat superfluous.
But, in general, when a class implements IDisposable
, the understanding is that you should Dispose()
of its instances as soon as you're fully ready and able. I'd posit this is particularly true in cases like HttpClient
wherein it's not explicitly documented as to whether resources or connections are being held onto/open. In the case wherein the connection will be reused again [soon], you'll want to forgo Dipose()
ing of it -- you're not "fully ready" in that case.
See also: IDisposable.Dispose Method and When to call Dispose
I could not use:
ansible_ssh_common_args='-o StrictHostKeyChecking=no'
in inventory file. It seems ansible does not consider this option in my case (ansible 2.0.1.0 from pip in ubuntu 14.04)
I decided to use:
server ansible_host=192.168.1.1 ansible_ssh_common_args= '-o UserKnownHostsFile=/dev/null'
It helped me.
Also you could set this variable in group instead for each host:
[servers_group:vars]
ansible_ssh_common_args='-o UserKnownHostsFile=/dev/null'
var el = document.getElementById('foo');
el.parentNode.innerHTML;
I think your document must be having enough space in the window to display its contents. That means there is no need to scroll down to see any more part of the document. In that case, document height would be equal to the window height.