Hexadecimal IP Address to String IP
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
uint32_t ip = 0x0AA40001;
string ip_str="";
int temp = 0;
for (int i = 0; i < 8; i++){
if (i % 2 == 0)
{
temp += ip & 15;
ip = ip >> 4;
}
else
{
stringstream ss;
temp += (ip & 15) * 16;
ip = ip >> 4;
ss << temp;
ip_str = ss.str()+"." + ip_str;
temp = 0;
}
}
ip_str.pop_back();
cout << ip_str;
}
Output:10.164.0.1
We can adjust the factor levels based on target
and use it in arrange
library(dplyr)
df %>% arrange(factor(name, levels = target))
# name value
#1 b TRUE
#2 c FALSE
#3 a TRUE
#4 d FALSE
Or order
it and use it in slice
df %>% slice(order(factor(name, levels = target)))
In your template, you have access to all the variables that are members of the current $scope
. So, tobedone
should be $scope.tobedone
, and then you can display it with {{tobedone}}
, or [[tobedone]]
in your case.
I found that, despite what the docs indicate, the only way to get this to work is like this:
$ids = array(...); // Array of your values
$qb->add('where', $qb->expr()->in('r.winner', $ids));
http://groups.google.com/group/doctrine-dev/browse_thread/thread/fbf70837293676fb
I don't see any mention of flexbox in here, so I will illustrate:
HTML
<div class="wrapper">
<div class="main">top</div>
<div class="footer">bottom</div>
</div>
CSS
.wrapper {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.main {
flex: 1;
}
.footer {
flex: 0;
}
You can remove this by adding !important to your outline.
button{
outline: none !important;
}
List<string> myCollection = new List<string>()
{
"Bob", "Bob","Alex", "Abdi", "Abdi", "Bob", "Alex", "Bob","Abdi"
};
myCollection.Sort();
foreach (var name in myCollection.Distinct())
{
Console.WriteLine(name + " " + myCollection.Count(x=> x == name));
}
output: Abdi 3 Alex 2 Bob 4
After trying everything here what worked for me was to grant execution permission to eclipse:
cd eclipse-installation-dir
sudo chmod +x eclipse
Using Eclipse Luna on Ubuntu 12.04 LTS.
I had the same issue using Windows, got if fixed by opening it in Notepad++ and changing the encoding from "UCS-2 LE BOM" to "UTF-8".
Just using strings, for me is a good solution, less problems with mysql. Detects the current format and changes it if necessary, this solution is only for spanish/french format and english format, without use php datetime function.
class dateTranslator {
public static function translate($date, $lang) {
$divider = '';
if (empty($date)){
return null;
}
if (strpos($date, '-') !== false) {
$divider = '-';
} else if (strpos($date, '/') !== false) {
$divider = '/';
}
//spanish format DD/MM/YYYY hh:mm
if (strcmp($lang, 'es') == 0) {
$type = explode($divider, $date)[0];
if (strlen($type) == 4) {
$date = self::reverseDate($date,$divider);
}
if (strcmp($divider, '-') == 0) {
$date = str_replace("-", "/", $date);
}
//english format YYYY-MM-DD hh:mm
} else {
$type = explode($divider, $date)[0];
if (strlen($type) == 2) {
$date = self::reverseDate($date,$divider);
}
if (strcmp($divider, '/') == 0) {
$date = str_replace("/", "-", $date);
}
}
return $date;
}
public static function reverseDate($date) {
$date2 = explode(' ', $date);
if (count($date2) == 2) {
$date = implode("-", array_reverse(preg_split("/\D/", $date2[0]))) . ' ' . $date2[1];
} else {
$date = implode("-", array_reverse(preg_split("/\D/", $date)));
}
return $date;
}
USE
dateTranslator::translate($date, 'en')
// Once upon a time there was a farmer
// He had multiple haystacks
$haystackOne = range(1, 10);
$haystackTwo = range(11, 20);
$haystackThree = range(21, 30);
// In one of these haystacks he lost a needle
$needle = rand(1, 30);
// He wanted to know in what haystack his needle was
// And so he programmed...
if (in_array($needle, $haystackOne)) {
echo "The needle is in haystack one";
} elseif (in_array($needle, $haystackTwo)) {
echo "The needle is in haystack two";
} elseif (in_array($needle, $haystackThree)) {
echo "The needle is in haystack three";
}
// The farmer now knew where to find his needle
// And he lived happily ever after
What I do is I want the page to stay after submit when there are errors...So I want the page to be reloaded :
($_SERVER["PHP_SELF"])
While I include the sript from a seperate file e.g
include_once "test.php";
I also read somewhere that
if(isset($_POST['submit']))
Is a beginners old fasion way of posting a form, and
if ($_SERVER['REQUEST_METHOD'] == 'POST')
Should be used (Not my words, read it somewhere)
You just need to supply a password. You can do it within the same command line with the following syntax:
openssl pkcs12 -export -in "path.p12" -out "newfile.pem" -passin pass:[password]
You will then be prompted for a password to encrypt the private key in your output file. Include the "nodes" option in the line above if you want to export the private key unencrypted (plaintext):
openssl pkcs12 -export -in "path.p12" -out "newfile.pem" -passin pass:[password] -nodes
More info: http://www.openssl.org/docs/apps/pkcs12.html
Use this code in your php script (first lines)
ini_set('allow_url_fopen',1);
Did you try:
$(this).is(':focus');
Take a look at Using jQuery to test if an input has focus it features some more examples
You could get a JavaScript object containing the parameters with something like this:
var regex = /[?&]([^=#]+)=([^&#]*)/g,
url = window.location.href,
params = {},
match;
while(match = regex.exec(url)) {
params[match[1]] = match[2];
}
The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by =
characters, and pairs themselves separated by &
characters (or an =
character for the first one). For your example, the above would result in:
{v: "123", p: "hello"}
Here's a working example.
You can add references to your model through command line in the following manner:
rails g migration add_column_to_tester user_id:integer
This will generate a migration file like :
class AddColumnToTesters < ActiveRecord::Migration
def change
add_column :testers, :user_id, :integer
end
end
This works fine every time i use it..
a=np.array([[1,2,3],[4,5,6]])
a.tolist()
tolist method mentioned above will return the nested Python list
Use iloc to access by position (rather than label):
In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])
In [12]: df
Out[12]:
A B
a 1 2
b 3 4
In [13]: df.iloc[0] # first row in a DataFrame
Out[13]:
A 1
B 2
Name: a, dtype: int64
In [14]: df['A'].iloc[0] # first item in a Series (Column)
Out[14]: 1
While the other answers are great and answer the question there is one thing to consider when using input type="submit"
and button
. With an input type="submit"
you cannot use a CSS pseudo element on the input but you can for a button!
This is one reason to use a button
element over an input when it comes to styling.
This worked for me:
h1 {
display: inline;
overflow: hidden;
}
div {
position: relative;
float: right;
}
It's similar to the approach of the media object, by Stubbornella.
Edit: As they comment below, you need to place the element that's going to float before the element that's going to wrap (the one in your first fiddle)
here is my soln to define the remote and local port and then write out to a file the received data, put this all in a class of your choice with the correct imports
static UdpClient sendClient = new UdpClient();
static int localPort = 49999;
static int remotePort = 49000;
static IPEndPoint localEP = new IPEndPoint(IPAddress.Any, localPort);
static IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), remotePort);
static string logPath = System.AppDomain.CurrentDomain.BaseDirectory + "/recvd.txt";
static System.IO.StreamWriter fw = new System.IO.StreamWriter(logPath, true);
private static void initStuff()
{
fw.AutoFlush = true;
sendClient.ExclusiveAddressUse = false;
sendClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
sendClient.Client.Bind(localEP);
sendClient.BeginReceive(DataReceived, sendClient);
}
private static void DataReceived(IAsyncResult ar)
{
UdpClient c = (UdpClient)ar.AsyncState;
IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
Byte[] receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);
fw.WriteLine(DateTime.Now.ToString("HH:mm:ss.ff tt") + " (" + receivedBytes.Length + " bytes)");
c.BeginReceive(DataReceived, ar.AsyncState);
}
static void Main(string[] args)
{
initStuff();
byte[] emptyByte = {};
sendClient.Send(emptyByte, emptyByte.Length, remoteEP);
}
I found a very good solution here, I'm using it with kotlin.
First, in the drawable folder you have to create item_count.xml
:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="8dp" />
<solid android:color="#f20000" />
<stroke
android:width="2dip"
android:color="#FFF" />
<padding
android:bottom="5dp"
android:left="5dp"
android:right="5dp"
android:top="5dp" />
</shape>
In your Activity_Main
Layout some like:
<RelativeLayout
android:id="@+id/badgeLayout"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_toRightOf="@+id/badge_layout1"
android:layout_gravity="end|center_vertical"
android:layout_marginEnd="5dp">
<RelativeLayout
android:id="@+id/relative_layout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="@+id/btnBadge"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@mipmap/ic_notification" />
</RelativeLayout>
<TextView
android:id="@+id/txtBadge"
android:layout_width="18dp"
android:layout_height="18dp"
android:layout_alignRight="@id/relative_layout1"
android:background="@drawable/item_count"
android:text="22"
android:textColor="#FFF"
android:textSize="7sp"
android:textStyle="bold"
android:gravity="center"/>
</RelativeLayout>
And you can modify like:
btnBadge.setOnClickListener { view ->
Snackbar.make(view,"badge click", Snackbar.LENGTH_LONG) .setAction("Action", null).show()
txtBadge.text = "0"
}
separate the classes with a space.
<button class="btn btn-success dropdown-toggle active" data-toggle="dropdown">Success <span class="caret"></span></button>
Took me some time to find the solution.
In case your server response correctly and the request is the problem, you should add withCredentials: true
to the xhrFields
in the request:
$.ajax({
url: url,
type: method,
// This is the important part
xhrFields: {
withCredentials: true
},
// This is the important part
data: data,
success: function (response) {
// handle the response
},
error: function (xhr, status) {
// handle errors
}
});
Note: jQuery >= 1.5.1 is required
Go to the terminal and regenerate the ssh key again. Type ssh-keygen
. It will ask you where you want to save it, type the path.
Then copy the public key to gitlabs platform. It usually starts with ssh-rsa.
Well that's a very interesting question. I would divide the two constants in your question according to their type. int MAX_COUNT
is a constant of primitive type while Logger log
is a non-primitive type.
When we are making use of a constant of a primitive types, we are mutating the constant only once in our code public static final in MAX_COUNT = 10
and we are just accessing the value of the constant elsewhere for(int i = 0; i<MAX_COUNT; i++)
. This is the reason we are comfortable with using this convention.
While in the case of non-primitive types, although, we initialize the constant in only one place private static final Logger log = Logger.getLogger(MyClass.class);
, we are expected to mutate or call a method on this constant elsewhere log.debug("Problem")
. We guys don't like to put a dot operator after the capital characters. After all we have to put a function name after the dot operator which is surely going to be a camel-case name. That's why LOG.debug("Problem")
would look awkward.
Same is the case with String
types. We are usually not mutating or calling a method on a String
constant in our code and that's why we use the capital naming convention for a String
type object.
echo N | copy /-y $(SolutionDir)SomeDir $(OutDir)
Both .ics and .vcs files are in ASCII. If you use "Save As" option to save a calendar entry (Appt, Meeting Request/Response/Postpone/Cancel and etc) in both .ics and .vcs format and use vimdiff, you can easily see the difference.
Both .vcs (vCal) and .ics (iCal) belongs to the same VCALENDAR camp, but .vcs file shows "VERSION:1.0" whereas .ics file uses "VERSION:2.0".
The spec for vCalendar v1.0 can be found at http://www.imc.org/pdi/pdiproddev.html. The spec for iCalendar (vCalendar v2.0) is in RFC5545. In general, the newer is better, and that is true for Outlook 2007 and onward, but not for Outlook 2003.
For Outlook 2003, the behavior is peculiar. It can save the same calendar entry in both .ics and .vcs format, but it only read & display .vcs file correctly. It can read .ics file but it omits some fields and does not display it in calendar mode. My guess is that back then Microsoft wanted to provide .ics to be compatible with Mac's iCal but not quite committed to v2.0 yet.
So I would say for Outlook 2003, .vcs is the native format.
Open up terminal and check what java version is currently set in your path variable.
You can do that by typing in your terminal
java -version // this will check your jre version.
javac -version // this will check your compiler version
If this shows incorrect java version but you have installed java 1.8 then you have to set path variable to the newer version of java.
To do that do add the line:
export JAVA_HOME=/path/to/java/jdk1.x
to ~/.bash_profile
(same as /Users/username/.bash_profile
)
Then do this from the terminal to set the new variable
source ~/.bash_profile
Also what's your eclipse.ini set to ?
-Dosgi.requiredJavaVersion=1.7
EDIT:
Please open up terminal and type
find / -name "java" // This should find all folder named java on your file system.
Also how did you install java in the first place ?
For excluding multiple file types, you can use '+' to concatenate other lists. For example:
xcopy /r /d /i /s /y /exclude:excludedfileslist1.txt+excludedfileslist2.txt C:\dev\apan C:\web\apan
Source: http://www.tech-recipes.com/rx/2682/xcopy_command_using_the_exclude_flag/
It's a function which is a member of a class:
class C:
def my_method(self):
print("I am a C")
c = C()
c.my_method() # Prints("I am a C")
Simple as that!
(There are also some alternative kinds of method, allowing you to control the relationship between the class and the function. But I'm guessing from your question that you're not asking about that, but rather just the basics.)
The obvious answer wasn't there in all the responses.
PHP has a neat streaming delimiter parser available made for exactly that purpose.
$fp = fopen("/path/to/the/file", "r+");
while (($line = stream_get_line($fp, 1024 * 1024, "\n")) !== false) {
echo $line;
}
fclose($fp);
You can always cancel()
the Notification
from whatever is being invoked by the action (e.g., in onCreate()
of the activity tied to the PendingIntent
you supply to addAction()
).
In Visual Studio 2010 Express, there is an option called "Show all Settings". Located at "Tools > Options", window.
If this option is not checked, the line number option will not be available. Make sure this option is checked like shown below. This will make lot of additional settings visible in the tree view to the left.
Now this will make the option "Tools > Options > Text Editor > C# > General > Line Editor" available. Check the "Line Number" option to make line numbers visible on Visual Studio 2010 Express.
Alternatively you can use the Protected Attributes gem, however this defeats the purpose of requiring strong params. However if you're upgrading an older app, Protected Attributes does provide an easy pathway to upgrade until such time that you can refactor the attr_accessible to strong params.
This is for others (like me :) ). Don't forget to add the spring tx jar/maven dependency. Also correct configuration in appctx is:
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"
, by mistake wrong configuration which others may have
xmlns:tx="http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"
i.e., extra "/spring-tx-3.1.xsd"
xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"
in other words what is there in xmlns(namespace) should have proper mapping in
schemaLocation (namespace vs schema).
namespace here is : http://www.springframework.org/schema/tx
schema Doc Of namespace is : http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
this schema of namespace later is mapped in jar to locate the path of actual xsd located in org.springframework.transaction.config
With the rabbitmq_management plugin installed you can run this to delete all the unwanted queues:
rabbitmqctl list_queues -p vhost_name |\
grep -v "fast\|medium\|slow" |\
tr "[:blank:]" " " |\
cut -d " " -f 1 |\
xargs -I {} curl -i -u guest:guest -H "content-type:application/json" -XDELETE http://localhost:15672/api/queues/<vhost_name>/{}
Let's break the command down:
rabbitmqctl list_queues -p vhost_name
will list all the queues and how many task they have currently.
grep -v "fast\|medium\|slow"
will filter the queues you don't want to delete, let's say we want to delete every queue without the words fast, medium or slow.
tr "[:blank:]" " "
will normalize the delimiter on rabbitmqctl between the name of the queue and the amount of tasks there are
cut -d " " -f 1
will split each line by the whitespace and pick the 1st column (the queue name)
xargs -I {} curl -i -u guest:guest -H "content-type:application/json" -XDELETE http://localhost:15672/api/queues/<vhost>/{}
will pick up the queue name and will set it into where we set the {}
character deleting all queues not filtered in the process.
Be sure the user been used has administrator permissions.
If you're using version 3.x of Bootstrap, the correct way to do this now is:
$('#myModal').on('hidden.bs.modal', function (e) {
// do something...
})
Scroll down to the events section to learn more.
http://getbootstrap.com/javascript/#modals-usage
This appears to remain unchanged for whenever version 4 releases (http://v4-alpha.getbootstrap.com/components/modal/#events), but if it does I'll be sure to update this post with the relevant information.
Use this to convert String to Blob. Where connection is the connection to db object.
String strContent = s;
byte[] byteConent = strContent.getBytes();
Blob blob = connection.createBlob();//Where connection is the connection to db object.
blob.setBytes(1, byteContent);
pop
mutates the dictionary.
>>> lol = {"hello": "gdbye"}
>>> lol.pop("hello")
'gdbye'
>>> lol
{}
If you want to keep the original you could just copy it.
It's better to use a SecureString:
var password = new SecureString();
var phPassword phPassword = Marshal.SecureStringToGlobalAllocUnicode(password);
IntPtr phUserToken;
LogonUser(username, domain, phPassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out phUserToken);
And:
Marshal.ZeroFreeGlobalAllocUnicode(phPassword);
password.Dispose();
Function definition:
private static extern bool LogonUser(
string pszUserName,
string pszDomain,
IntPtr pszPassword,
int dwLogonType,
int dwLogonProvider,
out IntPtr phToken);
Many devices with different screen sizes/ratios/resolutions have come out even in the last five years, including new types of iPhones and iPads. It would be very difficult to customize a website for each device.
Meanwhile, media queries for device-width
, device-height
, and device-aspect-ratio
have been deprecated, so they may not work in future browser versions. (Source: MDN)
TLDR: Design based on browser widths, not devices. Here's a good introduction to this topic.
If the table has already been created:
First do:
ALTER TABLE `table1_name` ADD UNIQUE( `column_name`);
Then:
ALTER TABLE `table1_name` ADD FOREIGN KEY (`column_name`) REFERENCES `table2_name`(`column_name`);
For elements with dynamic width it's possible to use transform: translateX(-100%);
to counter the horizontal percentage value. This leads to two possible solutions:
Transition from:
transform: translateX(0);
to
transform: translateX(calc(100vw - 100%));
#viewportPendulum {_x000D_
position: fixed;_x000D_
left: 0;_x000D_
top: 0;_x000D_
animation: 2s ease-in-out infinite alternate swingViewport;_x000D_
/* just for styling purposes */_x000D_
background: #c70039;_x000D_
padding: 1rem;_x000D_
color: #fff;_x000D_
font-family: sans-serif;_x000D_
}_x000D_
_x000D_
@keyframes swingViewport {_x000D_
from {_x000D_
transform: translateX(0);_x000D_
}_x000D_
to {_x000D_
transform: translateX(calc(100vw - 100%));_x000D_
}_x000D_
}
_x000D_
<div id="viewportPendulum">Viewport</div>
_x000D_
Transition from:
transform: translateX(0);
left: 0;
to
left: 100%;
transform: translateX(-100%);
#parentPendulum {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
animation: 2s ease-in-out infinite alternate swingParent;_x000D_
/* just for styling purposes */_x000D_
background: #c70039;_x000D_
padding: 1rem;_x000D_
color: #fff;_x000D_
font-family: sans-serif;_x000D_
}_x000D_
_x000D_
@keyframes swingParent {_x000D_
from {_x000D_
transform: translateX(0);_x000D_
left: 0;_x000D_
}_x000D_
to {_x000D_
left: 100%;_x000D_
transform: translateX(-100%);_x000D_
}_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
padding: 2rem 0;_x000D_
margin: 2rem 15%;_x000D_
background: #eee;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div id="parentPendulum">Parent</div>_x000D_
</div>
_x000D_
Note: This approach can easily be extended to work for vertical positioning. Visit example here.
If you're using ANT to build, this is dead-simple. Add the following to your build.xml:
<checksum file="${jarFile}" todir="${toDir}"/>
Where jarFile is the JAR you want to generate the MD5 against, and toDir is the directory you want to place the MD5 file.
I've gotten same problem. The servers logs showed:
DEBUG: <-- origin: null
I've investigated that and it occurred that this is not populated when I've been calling from file from local drive. When I've copied file to the server and used it from server - the request worked perfectly fine
Maybe something like this:
if "%~s0"=="%~s1" ( cd %~sp1 & shift ) else (
echo CreateObject^("Shell.Application"^).ShellExecute "%~s0","%~0 %*","","runas",1 >"%tmp%%~n0.vbs" & "%tmp%%~n0.vbs" & del /q "%tmp%%~n0.vbs" & goto :eof
)
if you want to use build-in functions:
=REGEXEXTRACT(cell("address";'Sheet1'!A1);"^'(.*)'!\$A\$1$")
Explanation:
cell("address";'Sheet1'!A1)
gives you the address of the sheet, output is 'Sheet1'!$A$1
. Now we need to extract the actual sheet name from this output. I'm using REGEXEXTRACT to match it by regex ^'(.*)'!\$A\$1$
, but you can either use more/less specific regex or use functions like SUBSTITUTE or REPLACE
htdocs
is your default document-root directory, so you have to use localhost/index.html
to see that html file. In other words, localhost
is mapped to xampp/htdocs
, so index.html
is at localhost
itself. You can change the location of document root by modifying httpd.conf
and restarting the server.
This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.
However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.
In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.
Here is a simple example based on a SAP system I have access to.
Public Sub SimpleSAPExport()
Set SapGuiAuto = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI
Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
Set session = SAPCon.Children(0) 'Get the first session (window) on that connection
'Start the transaction to view a table
session.StartTransaction "SE16"
'Select table T001
session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
session.findById("wnd[0]/tbar[1]/btn[7]").Press
'Set our selection criteria
session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
session.findById("wnd[0]/tbar[1]/btn[8]").press
'Click the export to file button
session.findById("wnd[0]/tbar[1]/btn[45]").press
'Choose the export format
session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
session.findById("wnd[1]/tbar[0]/btn[0]").press
'Choose the export filename
session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\Temp\"
'Export the file
session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub
To help find the names of elements such aswnd[1]/tbar[0]/btn[0]
you can use script recording.
Click the customize local layout button, it probably looks a bit like this:
Then find the Script Recording and Playback menu item.
Within that the More
button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.
The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI")
defines the SapGuiAuto object.
If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx
in the SAP GUI installation folder.
Try to put this line of code in your main projects gradle script:
configurations { all*.exclude group: 'com.android.support', module: 'support-v4' }
I have two libraries linked to my project and they where using 'com.android.support:support-v4:22.0.0'.
Hope it helps someone.
For variables, specifies that the type of the variable that is being declared will be automatically deduced from its initializer. For functions, specifies that the return type is a trailing return type or will be deduced from its return statements (since C++14).
Syntax
auto variable initializer (1) (since C++11)
auto function -> return type (2) (since C++11)
auto function (3) (since C++14)
decltype(auto) variable initializer (4) (since C++14)
decltype(auto) function (5) (since C++14)
auto :: (6) (concepts TS)
cv(optional) auto ref(optional) parameter (7) (since C++14)
Explanation
1) When declaring variables in block scope, in namespace scope, in initialization statements of for loops, etc., the keyword auto may be used as the type specifier.
Once the type of the initializer has been determined, the compiler determines the type that will replace the keyword auto using the rules for template argument deduction from a function call (see template argument deduction#Other contexts for details). The keyword auto may be accompanied by modifiers, such as const or &, which will participate in the type deduction. For example, given const auto& i = expr;
, the type of i is exactly the type of the argument u in an imaginary template template<class U> void f(const U& u)
if the function call f(expr)
was compiled. Therefore, auto&& may be deduced either as an lvalue reference or rvalue reference according to the initializer, which is used in range-based for loop.
If auto is used to declare multiple variables, the deduced types must match. For example, the declaration auto i = 0, d = 0.0;
is ill-formed, while the declaration auto i = 0, *p = &i;
is well-formed and the auto is deduced as int.
2) In a function declaration that uses the trailing return type syntax, the keyword auto does not perform automatic type detection. It only serves as a part of the syntax.
3) In a function declaration that does not use the trailing return type syntax, the keyword auto indicates that the return type will be deduced from the operand of its return statement using the rules for template argument deduction.
4) If the declared type of the variable is decltype(auto), the keyword auto is replaced with the expression (or expression list) of its initializer, and the actual type is deduced using the rules for decltype.
5) If the return type of the function is declared decltype(auto), the keyword auto is replaced with the operand of its return statement, and the actual return type is deduced using the rules for decltype.
6) A nested-name-specifier of the form auto:: is a placeholder that is replaced by a class or enumeration type following the rules for constrained type placeholder deduction.
7) A parameter declaration in a lambda expression. (since C++14) A function parameter declaration. (concepts TS)
Notes
Until C++11, auto had the semantic of a storage duration specifier.
Mixing auto variables and functions in one declaration, as in auto f() -> int, i = 0;
is not allowed.
For more info : http://en.cppreference.com/w/cpp/language/auto
Add column "a"
> df["a"] <- 0
> df
b c d a
1 1 2 3 0
2 1 2 3 0
3 1 2 3 0
Sort by column using colum name
> df <- df[c('a', 'b', 'c', 'd')]
> df
a b c d
1 0 1 2 3
2 0 1 2 3
3 0 1 2 3
Or sort by column using index
> df <- df[colnames(df)[c(4,1:3)]]
> df
a b c d
1 0 1 2 3
2 0 1 2 3
3 0 1 2 3
Goto project -->properties --> (in the dialog box that opens goto Java build path), and in order and export select android 4.1 (your new version) and select dependencies.
With Python 2, this doesn't work for non-English words in UTF-8. In this case decode('utf-8')
can help:
>>> s='????????'
>>> print s.lower()
????????
>>> print s.decode('utf-8').lower()
????????
It seems that in VBA macro code for an ActiveX checkbox control you use
If (ActiveSheet.OLEObjects("CheckBox1").Object.Value = True)
and for a Form checkbox control you use
If (ActiveSheet.Shapes("CheckBox1").OLEFormat.Object.Value = 1)
As someone who has written several libraries for consuming REST services, let me give you the client perspective on why I think wrapping the result in metadata is the way to go:
And a suggestion: Like the Twitter API, you should replace the page_number with a straight index/cursor. The reason is, the API allows the client to set the page size per-request. Is the returned page_number the number of pages the client has requested so far, or the number of the page given the last used page_size (almost certainly the later, but why not avoid such ambiguity altogether)?
If you can use LINQ you can use:
var e = enumerable.First();
This will throw an exception though if enumerable is empty: in which case you can use:
var e = enumerable.FirstOrDefault();
FirstOrDefault()
will return default(T)
if the enumerable is empty, which will be null
for reference types or the default 'zero-value' for value types.
If you can't use LINQ, then your approach is technically correct and no different than creating an enumerator using the GetEnumerator
and MoveNext
methods to retrieve the first result (this example assumes enumerable is an IEnumerable<Elem>
):
Elem e = myDefault;
using (IEnumerator<Elem> enumer = enumerable.GetEnumerator()) {
if (enumer.MoveNext()) e = enumer.Current;
}
Joel Coehoorn mentioned .Single()
in the comments; this will also work, if you are expecting your enumerable to contain exactly one element - however it will throw an exception if it is either empty or larger than one element. There is a corresponding SingleOrDefault()
method that covers this scenario in a similar fashion to FirstOrDefault()
. However, David B explains that SingleOrDefault()
may still throw an exception in the case where the enumerable contains more than one item.
Edit: Thanks Marc Gravell for pointing out that I need to dispose of my IEnumerator
object after using it - I've edited the non-LINQ example to display the using
keyword to implement this pattern.
You can't remove IEnumerable<T>
elements, but you can use the Enumerable.Skip Method
For anyone in the future looking for an answer, I would like to give a much clearer answer to the question.
# for making a tuple
my_tuple = (89, 32)
my_tuple_with_more_values = (1, 2, 3, 4, 5, 6)
# to concatenate tuples
another_tuple = my_tuple + my_tuple_with_more_values
print(another_tuple)
# (89, 32, 1, 2, 3, 4, 5, 6)
# getting a value from a tuple is similar to a list
first_val = my_tuple[0]
second_val = my_tuple[1]
# if you have a function called my_tuple_fun that returns a tuple,
# you might want to do this
my_tuple_fun()[0]
my_tuple_fun()[1]
# or this
v1, v2 = my_tuple_fun()
Hope this clears things up further for those that need it.
Diffuse is an easy to use three-way merge tool. It supports all of the platforms and version control systems you mentioned, and it can compare more than three files at the same time.
I am sure that this is JVM implemenation specific, but I was able to "influence" my JVM's default file.encoding by executing:
export LC_ALL=en_US.UTF-8
(running java version 1.7.0_80 on Ubuntu 12.04)
Also, if you type "locale" from your unix console, you should see more info there.
All the credit goes to http://www.philvarner.com/2009/10/24/unicode-in-java-default-charset-part-4/
Is there a method equivalent to getJSONArray in org.json so that I have proper error handling in case it isn't an array?
It depends on your input; i.e. the stuff you fetch from the URL. If the value of the "datasets" attribute is an associative array rather than a plain array, you will get a ClassCastException
.
But then again, the correctness of your old version also depends on the input. In the situation where your new version throws a ClassCastException
, the old version will throw JSONException
. Reference: http://www.json.org/javadoc/org/json/JSONObject.html#getJSONArray(java.lang.String)
Just do this way:-
$('ul li').on('click', function(e) {
alert($(this).index());
});
OR
$('ul li').click(function() {
alert($(this).index());
});
In SP2013 Online, I tried the filter conditions as Name
Contains
Folder_I_want_to_list
This showed me all the folders containing the Name
in their file path. It lists even sub-folder contents which wasn't available when i tried Name
equal to
Folder_I_want_to_list
Use JsonResponse
from django.http import JsonResponse
I think you can adapt the function to substract the two timestamps:
return EXTRACT(MINUTE FROM
TO_TIMESTAMP(to_char(p_date1,'DD-MON-YYYY HH:MI:SS'),'DD-MON-YYYY HH24:MI:SS')
-
TO_TIMESTAMP(to_char(p_date2,'DD-MON-YYYY HH:MI:SS'),'DD-MON-YYYY HH24:MI:SS')
);
I think you could simplify it by just using CAST(p_date as TIMESTAMP)
.
return EXTRACT(MINUTE FROM cast(p_date1 as TIMESTAMP) - cast(p_date2 as TIMESTAMP));
Remember dates and timestamps are big ugly numbers inside Oracle, not what we see in the screen; we don't need to tell him how to read them. Also remember timestamps can have a timezone defined; not in this case.
A (MySQLdb/PyMySQL-specific) difference worth noting when using a DictCursor
is that list(cursor)
will always give you a list, while cursor.fetchall()
gives you a list unless the result set is empty, in which case it gives you an empty tuple. This was the case in MySQLdb and remains the case in the newer PyMySQL, where it will not be fixed for backwards-compatibility reasons. While this isn't a violation of Python Database API Specification, it's still surprising and can easily lead to a type error caused by wrongly assuming that the result is a list, rather than just a sequence.
Given the above, I suggest always favouring list(cursor)
over cursor.fetchall()
, to avoid ever getting caught out by a mysterious type error in the edge case where your result set is empty.
You did a great job of summarizing what's awesome about Node.js. My feeling is that Node.js is especially suited for applications where you'd like to maintain a persistent connection from the browser back to the server. Using a technique known as "long-polling", you can write an application that sends updates to the user in real time. Doing long polling on many of the web's giants, like Ruby on Rails or Django, would create immense load on the server, because each active client eats up one server process. This situation amounts to a tarpit attack. When you use something like Node.js, the server has no need of maintaining separate threads for each open connection.
This means you can create a browser-based chat application in Node.js that takes almost no system resources to serve a great many clients. Any time you want to do this sort of long-polling, Node.js is a great option.
It's worth mentioning that Ruby and Python both have tools to do this sort of thing (eventmachine and twisted, respectively), but that Node.js does it exceptionally well, and from the ground up. JavaScript is exceptionally well situated to a callback-based concurrency model, and it excels here. Also, being able to serialize and deserialize with JSON native to both the client and the server is pretty nifty.
I look forward to reading other answers here, this is a fantastic question.
It's worth pointing out that Node.js is also great for situations in which you'll be reusing a lot of code across the client/server gap. The Meteor framework makes this really easy, and a lot of folks are suggesting this might be the future of web development. I can say from experience that it's a whole lot of fun to write code in Meteor, and a big part of this is spending less time thinking about how you're going to restructure your data, so the code that runs in the browser can easily manipulate it and pass it back.
Here's an article on Pyramid and long-polling, which turns out to be very easy to set up with a little help from gevent: TicTacToe and Long Polling with Pyramid.
Set up a server that exposes an HTTP url that reports the latest version, then use an AlarmManager to call that URL and see if the version on the device is the same as the latest version. If it isn't pop up a message or notification and send them to the market to upgrade.
There are some code examples: How to allow users to check for the latest app version from inside the app?
I think it's r+
, not rw
. I'm just a starter, and that's what I've seen in the documentation.
If you are interested in the lifecycle state of the specific instance of the activity, siliconeagle's solution looks correct except that the new "active" variable should be an instance variable, rather than static.
Instead of monkey patching or needlessly including large libraries, you can use refinements if you are using Ruby 2:
module HashExtensions
refine Hash do
def except!(*candidates)
candidates.each { |candidate| delete(candidate) }
self
end
def except(*candidates)
dup.remove!(candidates)
end
end
end
You can use this feature without affecting other parts of your program, or having to include large external libraries.
class FabulousCode
using HashExtensions
def incredible_stuff
delightful_hash.except(:not_fabulous_key)
end
end
open your git command line
put
git config --global user.email "[email protected]"
this command on command line and change email address put your own email which those use creating accout for github
hit enter
put git config --global user.name "Your Name"
use your own name insted of your name
hit enter
its work...
I had to use this
"C:\Program Files\Android\Android Studio\gradle\gradle-4.1"
Change the version if you have a different one.
After testing almost ever method listed in multiple style of browsers on multiple styles of cookies, I found almost nothing here works even 50%.
Please help correct as needed, but I'm going to throw my 2 cents in here. The following method breaks everything down and basically builds the cookie value string based on both the settings pieces as well as including a step by step build of the path string, starting with /
of course.
Hope this helps others and I hope any criticism may come in the form of perfecting this method. At first I wanted a simple 1-liner as some others sought, but JS cookies are one of those things not so easily dealt with.
;(function() {
if (!window['deleteAllCookies'] && document['cookie']) {
window.deleteAllCookies = function(showLog) {
var arrCookies = document.cookie.split(';'),
arrPaths = location.pathname.replace(/^\//, '').split('/'), // remove leading '/' and split any existing paths
arrTemplate = [ 'expires=Thu, 01-Jan-1970 00:00:01 GMT', 'path={path}', 'domain=' + window.location.host, 'secure=' ]; // array of cookie settings in order tested and found most useful in establishing a "delete"
for (var i in arrCookies) {
var strCookie = arrCookies[i];
if (typeof strCookie == 'string' && strCookie.indexOf('=') >= 0) {
var strName = strCookie.split('=')[0]; // the cookie name
for (var j=1;j<=arrTemplate.length;j++) {
if (document.cookie.indexOf(strName) < 0) break; // if this is true, then the cookie no longer exist
else {
var strValue = strName + '=; ' + arrTemplate.slice(0, j).join('; ') + ';'; // made using the temp array of settings, putting it together piece by piece as loop rolls on
if (j == 1) document.cookie = strValue;
else {
for (var k=0;k<=arrPaths.length;k++) {
if (document.cookie.indexOf(strName) < 0) break; // if this is true, then the cookie no longer exist
else {
var strPath = arrPaths.slice(0, k).join('/') + '/'; // builds path line
strValue = strValue.replace('{path}', strPath);
document.cookie = strValue;
}
}
}
}
}
}
}
showLog && window['console'] && console.info && console.info("\n\tCookies Have Been Deleted!\n\tdocument.cookie = \"" + document.cookie + "\"\n");
return document.cookie;
}
}
})();
You need to enclose that in <%! %> as follows:
<%!
public String getQuarter(int i){
String quarter;
switch(i){
case 1: quarter = "Winter";
break;
case 2: quarter = "Spring";
break;
case 3: quarter = "Summer I";
break;
case 4: quarter = "Summer II";
break;
case 5: quarter = "Fall";
break;
default: quarter = "ERROR";
}
return quarter;
}
%>
You can then invoke the function within scriptlets or expressions:
<%
out.print(getQuarter(4));
%>
or
<%= getQuarter(17) %>
InnoDB works slightly different that MyISAM and they both are viable options. You should use what you think it fits the project.
Some keypoints will be:
Notes:
Notes2: - I am reading this book "High performance MySQL", the author says "InnoDB loads data and creates indexes slower than MyISAM", this could also be a very important factor when deciding what to use.
CARL LANGE also showed how to get hidden, autoplaying audio in html5 on a iOS device. Works for me.
In HTML,
<div id="hideme">
<audio id="audioTag" controls>
<source src="/path/to/audio.mp3">
</audio>
</div>
with JS
<script type="text/javascript">
window.onload = function() {
var audioEl = document.getElementById("audioTag");
audioEl.load();
audioEl.play();
};
</script>
In CSS,
#hideme {display: none;}
What about this approach:
jQuery.fn.messagePlugin = function(){
var selectedObjects = this;
return {
saySomething : function(message){
$(selectedObjects).each(function(){
$(this).html(message);
});
return selectedObjects; // Preserve the jQuery chainability
},
anotherAction : function(){
//...
return selectedObjects;
}
};
}
// Usage:
$('p').messagePlugin().saySomething('I am a Paragraph').css('color', 'red');
The selected objects are stored in the messagePlugin closure, and that function returns an object that contains the functions associated with the plugin, the in each function you can perform the desired actions to the currently selected objects.
You can test and play with the code here.
Edit: Updated code to preserve the power of the jQuery chainability.
I faced the same problem in Derby IBM DB2 embedded database in a java desktop application, and after a day of searching I finally found how it's done :
SELECT days (table1.datecolomn) - days (current date) FROM table1 WHERE days (table1.datecolomn) - days (current date) > 5
for more information check this site
If you install just the JRE, it seems to be put at:
/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home
There is many way to watch multiple values :
//angular 1.1.4
$scope.$watchCollection(['foo', 'bar'], function(newValues, oldValues){
// do what you want here
});
or more recent version
//angular 1.3
$scope.$watchGroup(['foo', 'bar'], function(newValues, oldValues, scope) {
//do what you want here
});
Read official doc for more informations : https://docs.angularjs.org/api/ng/type/$rootScope.Scope
Through Configuration, you can do this:
Model1
{
int fk_one,
int fk_two
}
Model2
{
int pk_one,
int pk_two,
}
then in the context config
public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Model1>()
.HasRequired(e => e.Model2)
.WithMany(e => e.Model1s)
.HasForeignKey(e => new { e.fk_one, e.fk_two })
.WillCascadeOnDelete(false);
}
}
One of the way is Using below sql queries
--Size of All Table Space
--1. Used Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "USED SPACE(IN GB)" FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME
--2. Free Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "FREE SPACE(IN GB)" FROM USER_FREE_SPACE GROUP BY TABLESPACE_NAME
--3. Both Free & Used
SELECT USED.TABLESPACE_NAME, USED.USED_BYTES AS "USED SPACE(IN GB)", FREE.FREE_BYTES AS "FREE SPACE(IN GB)"
FROM
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS USED_BYTES FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME) USED
INNER JOIN
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS FREE_BYTES FROM USER_FREE_SPACE GROUP BY TABLESPACE_NAME) FREE
ON (USED.TABLESPACE_NAME = FREE.TABLESPACE_NAME);
The quick start guide that keyboardsurfer references will work if you need to get your project to build properly, but it leaves you with a dummy google-play-services project in your Eclipse workspace, and it doesn't properly link Eclipse to the Google Play Services Javadocs.
Here's what I did instead:
Install the Google Play Services SDK using the instructions in the Android Maps V2 Quick Start referenced above, or the instructions to Setup Google Play Services SDK, but do not follow the instructions to add Google Play Services into your project.
Right click on the project in the Package Explorer, select Properties to open the properties for your project.
(Only if you already followed the instructions in the quick start guide!) Remove the dependency on the google-play-services project:
Click on the Android category and remove the reference to the google-play-services project.
Click on the Java Build Path category, then the Projects tab and remove the reference to the google-play-services project.
Click on the Java Build Path category, then the Libraries tab.
Click Add External JARs... and select the google-play-services.jar file. This should be in [Your ADT directory]\sdk\extras\google\google_play_services\libproject\google-play-services_lib\libs.
Click on the arrow next to the new google-play-services.jar entry, and select the Javadoc Location item.
Click Edit... and select the folder containing the Google Play Services Javadocs. This should be in [Your ADT directory]\sdk\extras\google\google_play_services\docs\reference.
Still in the Java Build Path category, click on the Order and Export tab. Check the box next to the google-play-services.jar entry.
Click OK to save your project properties.
Your project should now have access to the Google Play Services library, and the Javadocs should display properly in Eclipse.
you can save the model in json and weights in a hdf5 file format.
# keras library import for Saving and loading model and weights
from keras.models import model_from_json
from keras.models import load_model
# serialize model to JSON
# the keras model which is trained is defined as 'model' in this example
model_json = model.to_json()
with open("model_num.json", "w") as json_file:
json_file.write(model_json)
# serialize weights to HDF5
model.save_weights("model_num.h5")
files "model_num.h5" and "model_num.json" are created which contain our model and weights
To use the same trained model for further testing you can simply load the hdf5 file and use it for the prediction of different data. here's how to load the model from saved files.
# load json and create model
json_file = open('model_num.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
# load weights into new model
loaded_model.load_weights("model_num.h5")
print("Loaded model from disk")
loaded_model.save('model_num.hdf5')
loaded_model=load_model('model_num.hdf5')
To predict for different data you can use this
loaded_model.predict_classes("your_test_data here")
Try simple & lightweight PathJS lib.
Simple example:
Path.map("#/page").to(function(){
alert('page!');
});
James Gosling likened designing Java to the following:
"There's this principle about moving, when you move from one apartment to another apartment. An interesting experiment is to pack up your apartment and put everything in boxes, then move into the next apartment and not unpack anything until you need it. So you're making your first meal, and you're pulling something out of a box. Then after a month or so you've used that to pretty much figure out what things in your life you actually need, and then you take the rest of the stuff -- forget how much you like it or how cool it is -- and you just throw it away. It's amazing how that simplifies your life, and you can use that principle in all kinds of design issues: not do things just because they're cool or just because they're interesting."
You can read the context of the quote here
Basically operator overloading is great for a class that models some kind of point, currency or complex number. But after that you start running out of examples fast.
Another factor was the abuse of the feature in C++ by developers overloading operators like '&&', '||', the cast operators and of course 'new'. The complexity resulting from combining this with pass by value and exceptions is well covered in the Exceptional C++ book.
Other way to get current Controller name in View
@ViewContext.Controller.ValueProvider.GetValue("controller").RawValue
For completeness sake, and for those that do not wish to use the Interface Builder, here's a way of creating the same table as in Suragch's answer entirely programatically - albeit with a different size and position.
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView = UITableView()
let animals = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
let cellReuseIdentifier = "cell"
override func viewDidLoad() {
super.viewDidLoad()
tableView.frame = CGRectMake(0, 50, 320, 200)
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
self.view.addSubview(tableView)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return animals.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as UITableViewCell!
cell.textLabel?.text = animals[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You tapped cell number \(indexPath.row).")
}
}
Make sure you have remembered to import UIKit
.
If you want to dump all collections, run this command:
mongodump -d {DB_NAME} -o /tmp
It will generate all collections data in json
and bson
extensions into /tmp/{DB_NAME}
directory
Edit: I have just explained logic to pair here. If anybody want to go with the complete code then see my another answer. I have answered here for logic only but I was not able to explain properly, So I have added another answer in the same thread.
Try this to do pairing:
If you are able to search the devices then this would be your next step
ArrayList<BluetoothDevice> arrayListBluetoothDevices = NEW ArrayList<BluetoothDevice>;
I am assuming that you have the list of Bluetooth devices added in the arrayListBluetoothDevices
:
BluetoothDevice bdDevice;
bdDevice = arrayListBluetoothDevices.get(PASS_THE_POSITION_TO_GET_THE_BLUETOOTH_DEVICE);
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
Log.i("Log","Paired");
}
} catch (Exception e)
{
e.printStackTrace();
}
The createBond()
method:
public boolean createBond(BluetoothDevice btDevice)
throws Exception
{
Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
Method createBondMethod = class1.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
Add this line into your Receiver in the ACTION_FOUND
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
arrayListBluetoothDevices.add(device);
}
You need the ?Rscript
command to run an R script from the terminal.
Check out http://stat.ethz.ch/R-manual/R-devel/library/utils/html/Rscript.html
Example
## example #! script for a Unix-alike
#! /path/to/Rscript --vanilla --default-packages=utils
args <- commandArgs(TRUE)
res <- try(install.packages(args))
if(inherits(res, "try-error")) q(status=1) else q()
You could use svcutil.exe to generate client code. This would include the definition of the service contract and any data contracts and fault contracts required.
Then, simply delete the client code: classes that implement the service contracts. You'll then need to implement them yourself, in your service.
Here is an Spinner subclass which overrides performClick() to show a dialog instead of a dropdown. No XML required. Give it a try, let me know if it works for you.
public class DialogSpinner extends Spinner {
public DialogSpinner(Context context) {
super(context);
}
@Override
public boolean performClick() {
new AlertDialog.Builder(getContext()).setAdapter((ListAdapter) getAdapter(),
new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
setSelection(which);
dialog.dismiss();
}
}).create().show();
return true;
}
}
For more information read this article: How To Make Android Spinner Options Popup In A Dialog
I struggled with the same problem where I was trying to execute an update query like the same as you did-
@Modifying
@Transactional
@Query(value = "UPDATE SAMPLE_TABLE st SET st.status=:flag WHERE se.referenceNo in :ids")
public int updateStatus(@Param("flag")String flag, @Param("ids")List<String> references);
This will work if you have put @EnableTransactionManagement
annotation on the main class.
Spring 3.1 introduces the @EnableTransactionManagement
annotation to be used in on @Configuration
classes and enable transactional support.
In contrast to what the accepted answer proposes, the documentation says that for JSONArray() you must use put(value)
no add(value)
.
https://developer.android.com/reference/org/json/JSONArray.html#put(java.lang.Object)
(Android API 19-27. Kotlin 1.2.50)
This can be done with tables:
<table cellpadding="0" cellspacing="0" width="100%" height="100%">
<tr height="0%"><td>
<div id="full">
<!--contents of 1 -->
</div>
</td></tr>
<tr><td>
<div id="someid">
<!--contents of 2 -->
</div>
</td></tr>
</table>
Then apply css to make someid fill the remaining space:
#someid {
height: 100%;
}
Now, I can just hear the angry shouts from the crowd, "Oh noes, he's using tables! Feed him to the lions!" Please hear me out.
Unlike the accepted answer which accomplishes nothing aside from making the container div the full height of the page, this solution makes div #2 fill the remaining space as requested in the question. If you need that second div to fill the full height allotted to it, this is currently the only way to do it.
But feel free to prove me wrong, of course! CSS is always better.
If you don't want to add a dependency on Guava (per Michael's answer) then this comparator is equivalent:
private static Comparator<String> ALPHABETICAL_ORDER = new Comparator<String>() {
public int compare(String str1, String str2) {
int res = String.CASE_INSENSITIVE_ORDER.compare(str1, str2);
if (res == 0) {
res = str1.compareTo(str2);
}
return res;
}
};
Collections.sort(list, ALPHABETICAL_ORDER);
And I think it is just as easy to understand and code ...
The last 4 lines of the method can written more concisely as follows:
return (res != 0) ? res : str1.compareTo(str2);
my experience:
in some situations the background image url have to be put separately for all page parts - I use:
var bgImageUrl = "url(../thirdparty/icons/android-circuit.jpg)";
...
$('#indexa').live('pageinit', function() {
$("#indexa").css("background-image",bgImageUrl);
$("#contenta").css("background-image",bgImageUrl);
$("#footera").css("background-image",bgImageUrl);
...
}
where "indexa" is the id of the whole page, and the "contenta" and "footera" are id-s of the content and footer respectively.
This works for sure in PhoneGap + jQuery Mobile
my way is to write an actual batch (saying "foo.bat") to finish the job; then create another "start.bat":
@echo off
cmd /k foo.bat
I find this is extremely useful when I set up one-time environment variables.
Place your script
inside the body tag
<body>
// Rest of html
<script>
function hideButton() {
$(".loading").hide();
}
function showButton() {
$(".loading").show();
}
</script>
< /body>
If you check this JSFIDDLE and click on javascript, you will see the load Type body
is selected
You can use pmap to report memory usage.
Synopsis:
pmap [ -x | -d ] [ -q ] pids...
with Swift 5 it's Simple and Super fast!!
You just need to add cocoa pods "BarcodeScanner" here is the full code
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '12.0'
target 'Simple BarcodeScanner'
do
pod 'BarcodeScanner'
end
Make sure add Camera permission in your .plist file
<key>NSCameraUsageDescription</key>
<string>Camera usage description</string>
And add Scanner and handle result in your ViewController this way
import UIKit
import BarcodeScanner
class ViewController: UIViewController, BarcodeScannerCodeDelegate, BarcodeScannerErrorDelegate, BarcodeScannerDismissalDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let viewController = BarcodeScannerViewController()
viewController.codeDelegate = self
viewController.errorDelegate = self
viewController.dismissalDelegate = self
present(viewController, animated: true, completion: nil)
}
func scanner(_ controller: BarcodeScannerViewController, didCaptureCode code: String, type: String) {
print("Product's Bar code is :", code)
controller.dismiss(animated: true, completion: nil)
}
func scanner(_ controller: BarcodeScannerViewController, didReceiveError error: Error) {
print(error)
}
func scannerDidDismiss(_ controller: BarcodeScannerViewController) {
controller.dismiss(animated: true, completion: nil)
}
}
Still and any question or challenges, please check sample application here with full source code
Your line:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.
Try
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
Due to the mixed comments about BuildConfig.DEBUG
, I used the following to disable crashlytics (and analytics) in debug mode :
update /app/build.gradle
android {
compileSdkVersion 25
buildToolsVersion "25.0.1"
defaultConfig {
applicationId "your.awesome.app"
minSdkVersion 16
targetSdkVersion 25
versionCode 100
versionName "1.0.0"
buildConfigField 'boolean', 'ENABLE_CRASHLYTICS', 'true'
}
buildTypes {
debug {
debuggable true
minifyEnabled false
buildConfigField 'boolean', 'ENABLE_CRASHLYTICS', 'false'
}
release {
debuggable false
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
then, in your code you detect the ENABLE_CRASHLYTICS
flag as follows:
if (BuildConfig.ENABLE_CRASHLYTICS)
{
// enable crashlytics and answers (Crashlytics by default includes Answers)
Fabric.with(this, new Crashlytics());
}
use the same concept in your app and rename ENABLE_CRASHLYTICS
to anything you want. I like this approach because I can see the flag in the configuration and I can control the flag.
Microsoft Visual Studio 2008 Service Pack 1 (iso)
http://www.microsoft.com/en-us/download/details.aspx?id=13276
Version: SP1 File Name: VS2008SP1ENUX1512962.iso Date Published: 8/11/2008 File Size: 831.3 MB
Supported Operating System
Windows Server 2003, Windows Server 2008, Windows Vista, Windows XP
Minimum: 1.6 GHz CPU, 384 MB RAM, 1024x768 display, 5400 RPM hard disk
Recommended: 2.2 GHz or higher CPU, 1024 MB or more RAM, 1280x1024 display, 7200 RPM or higher hard disk
On Windows Vista: 2.4 GHz CPU, 768 MB RAM
Maintain Internet connectivity during the installation of the service pack until seeing the “Installation Completed Successfully” message before disconnecting.
you can use this minified jQuery snippet to detect if your user is viewing using a mobile device. If you need to test for a specific device I’ve included a collection of JavaScript snippets below which can be used to detect various mobile handheld devices such as iPad, iPhone, iPod, iDevice, Andriod, Blackberry, WebOs and Windows Phone.
/**
* jQuery.browser.mobile (http://detectmobilebrowser.com/)
* jQuery.browser.mobile will be true if the browser is a mobile device
**/
(function(a){jQuery.browser.mobile=/android.+mobile|avantgo|bada/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)/|plucker|pocket|psp|symbian|treo|up.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|/(k|l|u)|50|54|e-|e/|-[a-w])|libw|lynx|m1-w|m3ga|m50/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(-|2|g)|yas-|your|zeto|zte-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);
Example Usage:
if(jQuery.browser.mobile)
{
console.log(‘You are using a mobile device!’);
}
else
{
console.log(‘You are not using a mobile device!’);
}
Detect iPad
var isiPad = /ipad/i.test(navigator.userAgent.toLowerCase());
if (isiPad)
{
…
}
Detect iPhone
var isiPhone = /iphone/i.test(navigator.userAgent.toLowerCase());
if (isiPhone)
{
…
}
Detect iPod
var isiPod = /ipod/i.test(navigator.userAgent.toLowerCase());
if (isiPod)
{
…
}
Detect iDevice
var isiDevice = /ipad|iphone|ipod/i.test(navigator.userAgent.toLowerCase());
if (isiDevice)
{
…
}
Detect Andriod
var isAndroid = /android/i.test(navigator.userAgent.toLowerCase());
if (isAndroid)
{
…
}
Detect Blackberry
var isBlackBerry = /blackberry/i.test(navigator.userAgent.toLowerCase());
if (isBlackBerry)
{
…
}
Detect WebOs
var isWebOS = /webos/i.test(navigator.userAgent.toLowerCase());
if (isWebOS)
{
…
}
Detect Windows Phone
var isWindowsPhone = /windows phone/i.test(navigator.userAgent.toLowerCase());
if (isWindowsPhone)
{
…
}
Corresponding to INSERT (Transact-SQL) (SQL Server 2005) you can't omit INSERT INTO dbo.Blah
and have to specify it every time or use another syntax/approach,
In MongoDB, the db.collection.remove() method removes documents from a collection. You can remove all documents from a collection, remove all documents that match a condition, or limit the operation to remove just a single document.
Source: Mongodb.
If you are using mongo sheel, just do:
db.Datetime.remove({})
In your case, you need:
You didn't show me the delete button, so this button is just an example:
<a class="button__delete"></a>
Change the controller to:
exports.destroy = function(req, res, next) {
Datetime.remove({}, function(err) {
if (err) {
console.log(err)
} else {
res.end('success');
}
}
);
};
Insert this ajax delete method in your client js file:
$(document).ready(function(){
$('.button__delete').click(function() {
var dataId = $(this).attr('data-id');
if (confirm("are u sure?")) {
$.ajax({
type: 'DELETE',
url: '/',
success: function(response) {
if (response == 'error') {
console.log('Err!');
}
else {
alert('Success');
location.reload();
}
}
});
} else {
alert('Canceled!');
}
});
});
Another possible reason for this error is that you have entire rows duplicated. If that is the case, the problem is solved by removing the duplicate rows.
If you mean the screen where you have that interpreter prompt >>>
you can do CTRL+L on Bash shell can help. Windows does not have equivalent. You can do
import os
os.system('cls') # on windows
or
os.system('clear') # on linux / os x
$.ajax
will work.
$.ajax({
url: 'script.php',
type: 'PUT',
success: function(response) {
//...
}
});
I'd use B because that in conjunction with worker process recycling means there'd only be a delay while it's recycling. This avoids the delay normally associated with initialization in response to the first request after idle. You also get to keep the benefits of recycling.
const areCommonElements = (arr1, arr2) => {
const arr2Set = new Set(arr2);
return arr1.some(el => arr2Set.has(el));
};
Or you can even have a better performance if you first find out which of these two arrays is longer and making Set
out for the longest array, while applying some
method on the shortest one:
const areCommonElements = (arr1, arr2) => {
const [shortArr, longArr] = (arr1.length < arr2.length) ? [arr1, arr2] : [arr2, arr1];
const longArrSet = new Set(longArr);
return shortArr.some(el => longArrSet.has(el));
};
In my case, I had to change the cell padding of an element that contained an input checkbox for a table that's being dynamically rendered with DataTables:
<td class="dt-center">
<input class="a" name="constCheck" type="checkbox" checked="">
</td>
After implementing the following line code within the initComplete function I was able to produce the correct padding, which fixed the rows from being displayed with an abnormally large height
$('tbody td:has(input.a)').css('padding', '0px');
Now, you can see that the correct styles are being applied to the parent element:
<td class=" dt-center" style="padding: 0px;">
<input class="a" name="constCheck" type="checkbox" checked="">
</td>
Essentially, this answer is an extension of @KP's answer, but the more collaboration of implementing this the better. In summation, I hope this helps someone else because it works! Lastly, thank you so much @KP for leading me in the right direction!
We had a situation where we needed to persist the URL hash across ASP.Net post backs. As the browser does not send the hash to the server by default, the only way to do it is to use some Javascript:
When the form submits, grab the hash (window.location.hash
) and store it in a server-side hidden input field Put this in a DIV with an id of "urlhash
" so we can find it easily later.
On the server you can use this value if you need to do something with it. You can even change it if you need to.
On page load on the client, check the value of this this hidden field. You will want to find it by the DIV it is contained in as the auto-generated ID won't be known. Yes, you could do some trickery here with .ClientID but we found it simpler to just use the wrapper DIV as it allows all this Javascript to live in an external file and be used in a generic fashion.
If the hidden input field has a valid value, set that as the URL hash (window.location.hash again
) and/or perform other actions.
We used jQuery to simplify the selecting of the field, etc ... all in all it ends up being a few jQuery calls, one to save the value, and another to restore it.
Before submit:
$("form").submit(function() {
$("input", "#urlhash").val(window.location.hash);
});
On page load:
var hashVal = $("input", "#urlhash").val();
if (IsHashValid(hashVal)) {
window.location.hash = hashVal;
}
IsHashValid()
can check for "undefined
" or other things you don't want to handle.
Also, make sure you use $(document).ready()
appropriately, of course.
Further from yuvi's excellent answer, I would like to add a small specific example on how to deal with this within Django (beyond any js that will be used). The example uses AjaxableResponseMixin
and assumes an Author model.
import json
from django.http import HttpResponse
from django.views.generic.edit import CreateView
from myapp.models import Author
class AjaxableResponseMixin(object):
"""
Mixin to add AJAX support to a form.
Must be used with an object-based FormView (e.g. CreateView)
"""
def render_to_json_response(self, context, **response_kwargs):
data = json.dumps(context)
response_kwargs['content_type'] = 'application/json'
return HttpResponse(data, **response_kwargs)
def form_invalid(self, form):
response = super(AjaxableResponseMixin, self).form_invalid(form)
if self.request.is_ajax():
return self.render_to_json_response(form.errors, status=400)
else:
return response
def form_valid(self, form):
# We make sure to call the parent's form_valid() method because
# it might do some processing (in the case of CreateView, it will
# call form.save() for example).
response = super(AjaxableResponseMixin, self).form_valid(form)
if self.request.is_ajax():
data = {
'pk': self.object.pk,
}
return self.render_to_json_response(data)
else:
return response
class AuthorCreate(AjaxableResponseMixin, CreateView):
model = Author
fields = ['name']
Source: Django documentation, Form handling with class-based views
The link to version 1.6 of Django is no longer available updated to version 1.11
Take the last digits only (up to 10) ignoring first "1".
function formatUSNumber(entry = '') {
const match = entry
.replace(/\D+/g, '').replace(/^1/, '')
.match(/([^\d]*\d[^\d]*){1,10}$/)[0]
const part1 = match.length > 2 ? `(${match.substring(0,3)})` : match
const part2 = match.length > 3 ? ` ${match.substring(3, 6)}` : ''
const part3 = match.length > 6 ? `-${match.substring(6, 10)}` : ''
return `${part1}${part2}${part3}`
}
example input / output as you type
formatUSNumber('+1333')
// (333)
formatUSNumber('333')
// (333)
formatUSNumber('333444')
// (333) 444
formatUSNumber('3334445555')
// (333) 444-5555
Building on rq's answer, I found this line does what I want:
git grep "search for something" $(git log -g --pretty=format:%h -S"search for something")
Which will report the commit ID, filename, and display the matching line, like this:
91ba969:testFile:this is a test
... Does anyone agree that this would be a nice option to be included in the standard git grep command?
Thanks for this post, it helped me a lot.
Dunno if it can help but I had the issue and thanks to you I found what I think is another way to solve it based on this boolean equivalence:
"A or B" is the same as "not(not A and not B)"
Thus:
IF [%var%] == [1] OR IF [%var%] == [2] ECHO TRUE
Becomes:
IF not [%var%] == [1] IF not [%var%] == [2] ECHO FALSE
We've started to use Find Bugs to help identify some of the funk in our codebase's target-rich environment for refactorings. I would also consider Structure 101 to identify spots in your codebase's architecture that are too complicated, so you know where the real swamps are.
Try the below:
myNewFunction = function(id, index) {
var selection = document.getElementById(id);
alert(selection.options[index].innerHTML);
};
See here jsfiddle sample
If you don't have ReSharper installed and still want to use the shortcut Shift
+Alt
+L
to move focus to the current file in Solution Explorer in Visual Studio 2013 then please follow these steps:
In the Show commands containing box type "solutionexplorer" and then in the list below look for the SyncWithActiveDocument command:
Click in textbox under "Press short keys" label and press: Shift
+Alt
+L
and click the Assign button and you are done:
To verify open any file in Visual Studio and press the shortcut keys Shift
+Alt
+L
and you'll see the file in the solution explorer. Enjoy!
I was having same issue, way i have resolved is:
opened the MySQL installer. i was having a Reconfigure link on MYSQL Server row.
Clicked on it, it does reinstalled MySQL Server. after that opened MySQL Workbench, and it was working fine.
If you need to clear the values of $_SESSION
, set the array equal to an empty array:
$_SESSION = array();
Of course, you can't access the values of $_SESSION
on another page once you call session_destroy
, so it doesn't matter that much.
Try the following:
session_destroy();
$_SESSION = array(); // Clears the $_SESSION variable
My /var/log/apache2 folder was 35g and some logs in /var/log totaled to be the other 5g of my 40g hard drive. I cleared out all the *.gz logs and after making sure the other logs werent going to do bad things if I messed with them, i just cleared them too.
echo "clear" > access.log
etc.
You can check if the constant's already defined using:
<?php
if (!defined('MYCONST'))
define('MYCONST', 'Weeha!');
?>
On Arch, i fix like this:
sudo ln -s /usr/lib/libncursesw.so.6 /usr/lib/libtinfo.so.6
Job Import plugin is the easy way here to import jobs from another Jenkins instance. Just need to provide the URL of the source Jenkins instance. The Remote Jenkins URL can take any of the following types of URLs:
http://$JENKINS
- get all jobs on remote instance
http://$JENKINS/job/$JOBNAME
- get a single job
http://$JENKINS/view/$VIEWNAME
- get all jobs in a particular view
https://stackoverflow.com/a/44845810/10480776 @Edison D'souza's answer was exactly what I was looking for. However, it was only replacing the first occurrence of the string. Here was my solution to handling multiple <br/>
tags:
<Typography style={{ whiteSpace: "pre-line" }}>
{shortDescription.split("<br/>").join("\n")}
</Typography>
Sorry, I couldn't comment on his post due to the reputation score limitation.
In my case it was OneTab chrome extension.
// Array of doubles
double[] array_doubles = {2.5, 6.2, 8.2, 4846.354, 9.6};
// First position
double firstNum = array_doubles[0]; // 2.5
// Last position
double lastNum = array_doubles[array_doubles.length - 1]; // 9.6
This is the same in any array.
You could use PIL to create (and display) an image:
from PIL import Image
import numpy as np
w, h = 512, 512
data = np.zeros((h, w, 3), dtype=np.uint8)
data[0:256, 0:256] = [255, 0, 0] # red patch in upper left
img = Image.fromarray(data, 'RGB')
img.save('my.png')
img.show()
demo
branch into master
git fetch --all
demo
branch on localgit pull origin demo
master
branch. This branch will be completely changed with the code on demo
branchgit checkout master
master
branch and run this command.git reset --hard origin/demo
reset
means you will be resetting current branch
--hard
is a flag that means it will be reset without raising any merge conflict
origin/demo
will be the branch that will be considered to be the code that will forcefully overwrite current master
branch
The output of the above command will show you your last commit message on origin/demo
or demo
branch
Then, in the end, force push the code on the master
branch to your remote repo.
git push --force
I think, the differences between ArrayList
and List<T>
are:
List<T>
, where T is value-type is faster than ArrayList
. This is
because List<T>
avoids boxing/unboxing (where T is value-type).ArrayList
used just for backward
compatibility. (is not a real difference, but i think it is
important note).ArrayList
then List<T>
ArrayList
has IsSynchronized
property. So, It is easy
to create and use syncronised ArrayList
. I didin't found IsSynchronized
property for List<T>
. Also Keep in mind this type of synchronization is relatively inefficient, msdn):
var arraylist = new ArrayList();
var arrayListSyncronized = ArrayList.Synchronized(arraylist
Console.WriteLine($"syncronized {arraylist.IsSynchronized}");
Console.WriteLine($"syncronized {arrayListSyncronized.IsSynchronized}");
var list = new List<object>();
var listSyncronized = ArrayList.Synchronized(list);
Console.WriteLine($"syncronized {list.IsSynchronized}");//error, no such prop
Console.WriteLine($"syncronized {list.IsSynchronized}");//error, no such prop
ArrayList
has ArrayList.SyncRoot
property which can be used for syncronisation (msdn). List<T>
hasn't SyncRoot
property, so in
the following construction you need to use some object if you use List<T>
:
ArrayList myCollection = new ArrayList();
lock(myCollection.SyncRoot) // ofcourse you can use another object for this goal
{
foreach (object item in myCollection)
{
// ...
}
}
df = pandas.DataFrame({'g':[1]}, index=['isStop'])
#df.loc['g']
if 'g' in df.index:
print("find g")
if 'isStop' in df.index:
print("find a")
According to this link Set default date of jquery datepicker, the other solution is
var d = new Date();
var currDate = d.getDate();
var currMonth = d.getMonth();
var currYear = d.getFullYear();
var dateStr = currDate + "-" + currMonth + "-" + currYear;
$("#datepicker").datepicker(({dateFormat: "dd-mm-yy" autoclose: true, defaultDate: dateStr });
Could it be that you have not entered a commit message? According to their twitter feed: "New functionality added. Block users from committing work without writing a log message. Find in the resources section of your control panel".
If you want to solve this without using Ajax, use the FileReader()
Web API.
Example implementation:
.csv
filefunction readSingleFile(e) {_x000D_
var file = e.target.files[0];_x000D_
if (!file) {_x000D_
return;_x000D_
}_x000D_
_x000D_
var reader = new FileReader();_x000D_
reader.onload = function(e) {_x000D_
var contents = e.target.result;_x000D_
displayContents(contents);_x000D_
displayParsed(contents);_x000D_
};_x000D_
reader.readAsText(file);_x000D_
}_x000D_
_x000D_
function displayContents(contents) {_x000D_
var element = document.getElementById('file-content');_x000D_
element.textContent = contents;_x000D_
}_x000D_
_x000D_
function displayParsed(contents) {_x000D_
const element = document.getElementById('file-parsed');_x000D_
const json = contents.split(',');_x000D_
element.textContent = JSON.stringify(json);_x000D_
}_x000D_
_x000D_
document.getElementById('file-input').addEventListener('change', readSingleFile, false);
_x000D_
<input type="file" id="file-input" />_x000D_
_x000D_
<h3>Raw contents of the file:</h3>_x000D_
<pre id="file-content">No data yet.</pre>_x000D_
_x000D_
<h3>Parsed file contents:</h3>_x000D_
<pre id="file-parsed">No data yet.</pre>
_x000D_
I'm not sure whether this is the best way to do it, but you could specify a negative text-indent
:
li {
text-indent: -4px;
}
...where your HTML code looks like:
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
(Tested in Safari 4.0.4 and Firefox 3.0.11.)
Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.
Let me explain using step-by-step guidance.
First, download the source code from https://github.com/rmtheis/tess-two.
Import all three projects. After importing you will get an error.
To solve the error you have to create a res
folder in the tess-two project
First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"
After doing this in all three project the error should be gone.
Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.
Now you just need to import it into your workspace, but first you have to download android-ndk from this site:
http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file
Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable
Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture
done it
Now open cmd and go to on D:\Android Workspace\tess-two like below
If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:
Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest
Import test-two in this and run OCRTest and run it; you will get the best example of OCR.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
std::string input = "abc,def, ghi";
std::istringstream ss(input);
std::string token;
size_t pos=-1;
while(ss>>token) {
while ((pos=token.rfind(',')) != std::string::npos) {
token.erase(pos, 1);
}
std::cout << token << '\n';
}
}
In Eclipse, right click on your project, go to Maven> Update projetc. Wait and the error will disappear. This is already configured correctly the version of Java for this project.
One of your requirements is to preserve the original lists. If you create a new list and use addAll()
, you are effectively doubling the number of references to the objects in your lists. This could lead to memory problems if your lists are very large.
If you don't need to modify the concatenated result, you can avoid this using a custom list implementation. The custom implementation class is more than one line, obviously...but using it is short and sweet.
CompositeUnmodifiableList.java:
public class CompositeUnmodifiableList<E> extends AbstractList<E> {
private final List<E> list1;
private final List<E> list2;
public CompositeUnmodifiableList(List<E> list1, List<E> list2) {
this.list1 = list1;
this.list2 = list2;
}
@Override
public E get(int index) {
if (index < list1.size()) {
return list1.get(index);
}
return list2.get(index-list1.size());
}
@Override
public int size() {
return list1.size() + list2.size();
}
}
Usage:
List<String> newList = new CompositeUnmodifiableList<String>(listOne,listTwo);
I am looking for a way to create a select without repeating the conditional query.
I'm assuming that you don't want to repeat Foo-stuff+bar
. You could put your calculation into a derived table:
SELECT CASE WHEN a.TestValue > 2 THEN a.TestValue ELSE 'Fail' END
FROM (SELECT (Foo-stuff+bar) AS TestValue FROM MyTable) AS a
A common table expression would work just as well:
WITH a AS (SELECT (Foo-stuff+bar) AS TestValue FROM MyTable)
SELECT CASE WHEN a.TestValue > 2 THEN a.TestValue ELSE 'Fail' END
FROM a
Also, each part of your switch should return the same datatype, so you may have to cast one or more cases.
TL;DR If some arguments in your test are null
, be sure to mock the parameter call with isNull()
instead of anyXXX()
.
I got this error when upgrading from Spring boot 1.5.x to 2.1.x. Spring boot ships with its own Mockito, which is now also upgraded to 2.x (see e.g. Dependencies of Spring boot 2.1.2)
Mockito has changed the behavior for the anyXXX()
method, where XXX
is String
, Long
, etc. Here is the javadoc of anyLong()
:
Since Mockito 2.1.0, only allow valued
Long
, thusnull
is not anymore a valid value As primitive wrappers are nullable, the suggested API to matchnull
wrapper would be#isNull()
. We felt this change would make tests harness much safer that it was with Mockito 1.x.
I'd suggest you debug to the point where your mock is about to be called and inspect, whether at least one argument is null
. In that case make sure, that you prepare your mock with isNull()
instead of e.g. anyLong()
.
So this:
when(MockedClass.method(anyString());
becomes:
when(MockedClass.method(isNull());
You might want to check the GC.GetTotalMemory method.
It retrieves the number of bytes currently thought to be allocated by the garbage collector.
We are used to
class ClassTypeA implements InterfaceTypeA {}
class ClassTypeB extends ClassTypeA {}
and any slight deviation from these rules greatly confuses us.
The syntax of a type bound is defined as
TypeBound:
extends TypeVariable
extends ClassOrInterfaceType {AdditionalBound}
(JLS 12 > 4.4. Type Variables > TypeBound
)
If we were to change it, we would surely add the implements
case
TypeBound:
extends TypeVariable
extends ClassType {AdditionalBound}
implements InterfaceType {AdditionalBound}
and end up with two identically processed clauses
ClassOrInterfaceType:
ClassType
InterfaceType
(JLS 12 > 4.3. Reference Types and Values > ClassOrInterfaceType
)
except we would also need to take care of implements
, which would complicate things further.
I believe it's the main reason why extends ClassOrInterfaceType
is used instead of extends ClassType
and implements InterfaceType
- to keep things simple within the complicated concept. The problem is we don't have the right word to cover both extends
and implements
and we definitely don't want to introduce one.
<T is ClassTypeA>
<T is InterfaceTypeA>
Although extends
brings some mess when it goes along with an interface, it's a broader term and it can be used to describe both cases. Try to tune your mind to the concept of extending a type (not extending a class, not implementing an interface). You restrict a type parameter by another type and it doesn't matter what that type actually is. It only matters that it's its upper bound and it's its supertype.
I'd generally recommend you leave the formatting up to your front-end code and just return the data as-is from SQL. However, to do it in SQL, I'd recommend you create a user-defined function to format it. Something like this:
CREATE FUNCTION [dbo].[fnFormatPhoneNumber](@PhoneNo VARCHAR(20))
RETURNS VARCHAR(25)
AS
BEGIN
DECLARE @Formatted VARCHAR(25)
IF (LEN(@PhoneNo) <> 10)
SET @Formatted = @PhoneNo
ELSE
SET @Formatted = LEFT(@PhoneNo, 3) + '-' + SUBSTRING(@PhoneNo, 4, 3) + '-' + SUBSTRING(@PhoneNo, 7, 4)
RETURN @Formatted
END
GO
Which you can then use like this:
SELECT [dbo].[fnFormatPhoneNumber](PhoneNumber) AS PhoneNumber
FROM SomeTable
It has a safeguard in, in case the phone number stored isn't the expected number of digits long, is blank, null etc - it won't error.
EDIT: Just clocked on you want to update your existing data. The main bit that's relevant from my answer then is that you need to protect against "dodgy"/incomplete data (i.e. what if some existing values are only 5 characters long)
I wrote this trying to solve the same problem:
https://github.com/robtandy/randomdict
It has O(1) random access to keys, values, and items.
Always use parseInt
with a radix (base) as the second parameter, or you will get unexpected results:
var number = parseInt($(this).find('.number').text(), 10);
A popular variation however is to use +
as a unitary operator. This will always convert with base 10 and never throw an error, just return zero NaN
which can be tested with the function isNaN()
if it's an invalid number:
var number = +($(this).find('.number').text());
Given the declarations
char *s0 = "hello world";
char s1[] = "hello world";
assume the following hypothetical memory map:
0x01 0x02 0x03 0x04 0x00008000: 'h' 'e' 'l' 'l' 0x00008004: 'o' ' ' 'w' 'o' 0x00008008: 'r' 'l' 'd' 0x00 ... s0: 0x00010000: 0x00 0x00 0x80 0x00 s1: 0x00010004: 'h' 'e' 'l' 'l' 0x00010008: 'o' ' ' 'w' 'o' 0x0001000C: 'r' 'l' 'd' 0x00
The string literal "hello world"
is a 12-element array of char
(const char
in C++) with static storage duration, meaning that the memory for it is allocated when the program starts up and remains allocated until the program terminates. Attempting to modify the contents of a string literal invokes undefined behavior.
The line
char *s0 = "hello world";
defines s0
as a pointer to char
with auto storage duration (meaning the variable s0
only exists for the scope in which it is declared) and copies the address of the string literal (0x00008000
in this example) to it. Note that since s0
points to a string literal, it should not be used as an argument to any function that would try to modify it (e.g., strtok()
, strcat()
, strcpy()
, etc.).
The line
char s1[] = "hello world";
defines s1
as a 12-element array of char
(length is taken from the string literal) with auto storage duration and copies the contents of the literal to the array. As you can see from the memory map, we have two copies of the string "hello world"
; the difference is that you can modify the string contained in s1
.
s0
and s1
are interchangeable in most contexts; here are the exceptions:
sizeof s0 == sizeof (char*)
sizeof s1 == 12
type of &s0 == char **
type of &s1 == char (*)[12] // pointer to a 12-element array of char
You can reassign the variable s0
to point to a different string literal or to another variable. You cannot reassign the variable s1
to point to a different array.
I can't speak for the 2nd or 3rd, but if you install Node first, Sublime-HTMLPrettify works pretty well. You have to setup your own key shortcut once it is installed. One thing I noticed on Windows, you may need to edit your path for Node in the %PATH% variable if it is already long (I think the limit is 1024 for the %PATH% variable, and anything after that is ignored.)
There is a Windows bug, but in the issues there is a fix for it. You'll need to edit the HTMLPrettify.py file - https://github.com/victorporof/Sublime-HTMLPrettify/issues/12
It's the same way you run it from command line. Just put that "command line" into a ".bat" file.
So, if you use java -cp .;foo.jar Bar
, put that into a .bat file as
@echo off
java -cp .;foo.jar Bar
Very simple implementation (only basic functionality) based on CSS and one line of JavaScript code.
.dropdown {
position: relative;
width: 200px;
}
.dropdown select {
width: 100%;
}
.dropdown > * {
box-sizing: border-box;
height: 1.5em;
}
.dropdown input {
position: absolute;
width: calc(100% - 20px);
}
_x000D_
<div class="dropdown">
<input type="text" />
<select onchange="this.previousElementSibling.value=this.value; this.previousElementSibling.focus()">
<option>This is option 1</option>
<option>Option 2</option>
</select>
</div>
_x000D_
Please note: it uses previousElementSibling()
which is not supported in older browsers (below IE9)
Based on Rohith Nandakumar's solution, I did something of my own to copy files from a subfolder of assets (i.e. "assets/MyFolder"). Also, I'm checking if the file already exists in sdcard before trying to copy again.
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("MyFolder");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
if (files != null) for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("MyFolder/"+filename);
File outFile = new File(getExternalFilesDir(null), filename);
if (!(outFile.exists())) {// File does not exist...
out = new FileOutputStream(outFile);
copyFile(in, out);
}
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
Until I get a better option, this is the most "bootstrappy" answer I can work out:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/6cbrjrt5/
I have switched to using LESS and including the Bootstrap Source NuGet package to ensure compatibility (by giving me access to the bootstrap variables.less
file:
in _layout.cshtml master page
body-content
containernavbar-fixed-bottom
on the footer<hr/>
before the footer (as now redundant)Relevant page HTML:
<div class="container-fluid body-content">
@RenderBody()
</div>
<footer class="navbar-fixed-bottom">
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
In Site.less
HTML
and BODY
heights to 100%BODY
overflow
to hidden
body-content
div position
to absolute
body-content
div top
to @navbar-height
instead of hard-wiring valuebody-content
div bottom
to 30px
.body-content
div left
and right
to 0body-content
div overflow-y
to auto
Site.less
html {
height: 100%;
body {
height: 100%;
overflow: hidden;
.container-fluid.body-content {
position: absolute;
top: @navbar-height;
bottom: 30px;
right: 0;
left: 0;
overflow-y: auto;
}
}
}
The remaining problem is there seems to be no defining variable for the footer height
in bootstrap. If someone call tell me if there is a magic 30px variable defined in Bootstrap I would appreciate it.
I think preprocessing is the way to go. You could use Notepad++ which has a regular expression replace option.
For example, if your file were like this:
"1,234","123","1,234"
"234","123","1,234"
123,456,789
Then, you could use the regular expression "([0-9]+),([0-9]+)"
and replace it with \1\2
1234,"123",1234
"234","123",1234
123,456,789
Then you could use x <- read.csv(file="x.csv",header=FALSE)
to read the file.
The answer here worked better for me as it isolates the search on the hashtag, not just returning results that contain the search string. In the answer above you would still need to parse the JSON response to see if the entities.hashtags array is not empty.
Edward,
You can modify the code in your example like this:
var playerShip:PlayerShip!
var deltaPoint = CGPointZero
init(size: CGSize)
{
super.init(size: size)
playerLayerNode.addChild(playerShip)
}
This is using an implicitly unwrapped optional.
In documentation we can read:
"As with optionals, if you don’t provide an initial value when you declare an implicitly unwrapped optional variable or property, it’s value automatically defaults to nil."
Thanks to @HBP for paving the way here!
I found this to add a little flexibility to the solution.
The RegEx has been updated to accommodate times before noon.
This solution allows you to pass any string to it. As long as a valid time (in this format 18:00 || 18:00:00 || 3:00 || 3:00:00) is somewhere in that string, you're good to go.
Note: you can use just the militaryToTweleveHourConverter
or take the guts out of the parseTime
variable. However, I'm formatting a date from a database with date-fns
then passing that formatted date to the converter.
Totally works. Hope this helps.
import dateFns from 'date-fns';
//* +---------------------------+
//* Format ex. Sat 1/1/18 1:00pm
//* +---------------------------+
const formatMonthDayYearTime = date =>
militaryToTweleveHourConverter(
dateFns.format(new Date(date), 'ddd M/DD/YY H:mm')
);
//* +-------------------------------+
//* Convert MILITARY TIME to 12 hour
//* +-------------------------------+
const militaryToTweleveHourConverter = time => {
const getTime = time.split(' ');
const parseTime = getTime.map(res => {
// Check for correct time format and split into components or return non-time units unaltered
let timeUnit = res
.toString()
.match(/^([\d]|[0-1]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [res];
console.log('timeUnit', timeUnit);
// If the time format is matched, it will break the components into an array
// ie. ["19:00", "19", ":", "00", undefined]
if (timeUnit.length > 1) {
// Remove full string match value
timeUnit = timeUnit.slice(1);
// Set am/pm and assign it to the last index in the array
timeUnit[5] = timeUnit[0] < 12 ? 'am' : 'pm';
// Adjust hours by subtracting 12 from anything greater than 12 and replace the value in the hours index
timeUnit[0] = timeUnit[0] % 12 || 12;
}
// return adjusted time or original string
return timeUnit.join('');
});
// Re-assemble the array pieces into a string
return parseTime.join(' ');
};
console.log(formatMonthDayYearTime('Sat 9/17/18 18:30'));
// console log returns the following
// Mon 9/17/18 6:30pm
console.log(militaryToTweleveHourConverter('18:30'));
// console log returns the following
// 6:30pm
console.log(militaryToTweleveHourConverter('18:30:09'));
// console log returns the following
// 6:30:09pm
console.log(militaryToTweleveHourConverter('8:30:09'));
// console log returns the following
// 8:30:09am
This basically has to do with the hardware architecture (i.e. RAM and caches).
If you don't use synchronized
together with wait()
or notify()
, another thread could enter the same block instead of waiting for the monitor to enter it. Moreover, when e.g. accessing an array without a synchronized block, another thread may not see the changement to it...actually another thread will not see any changements to it when it already has a copy of the array in the x-level cache (a.k.a. 1st/2nd/3rd-level caches) of the thread handling CPU core.
But synchronized blocks are only one side of the medal: If you actually access an object within a synchronized context from a non-synchronized context, the object still won't be synchronized even within a synchronized block, because it holds an own copy of the object in its cache. I wrote about this issues here: https://stackoverflow.com/a/21462631 and When a lock holds a non-final object, can the object's reference still be changed by another thread?
Furthermore, I'm convinced that the x-level caches are responsible for most non-reproducible runtime errors. That's because the developers usually don't learn the low-level stuff, like how CPU's work or how the memory hierarchy affects the running of applications: http://en.wikipedia.org/wiki/Memory_hierarchy
It remains a riddle why programming classes don't start with memory hierarchy and CPU architecture first. "Hello world" won't help here. ;)
In addition to the previous answers, here is a way to calculate the distance inside a SELECT:
CREATE FUNCTION Get_Distance
(
@La1 float , @Lo1 float , @La2 float, @Lo2 float
)
RETURNS TABLE
AS
RETURN
-- Distance in Meters
SELECT GEOGRAPHY::Point(@La1, @Lo1, 4326).STDistance(GEOGRAPHY::Point(@La2, @Lo2, 4326))
AS Distance
GO
Usage:
select Distance
from Place P1,
Place P2,
outer apply dbo.Get_Distance(P1.latitude, P1.longitude, P2.latitude, P2.longitude)
Scalar functions also work but they are very inefficient when computing large amount of data.
I hope this might help someone.
/**_x000D_
* Add a URL parameter _x000D_
* @param {string} url _x000D_
* @param {string} param the key to set_x000D_
* @param {string} value _x000D_
*/_x000D_
var addParam = function(url, param, value) {_x000D_
param = encodeURIComponent(param);_x000D_
var a = document.createElement('a');_x000D_
param += (value ? "=" + encodeURIComponent(value) : ""); _x000D_
a.href = url;_x000D_
a.search += (a.search ? "&" : "") + param;_x000D_
return a.href;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Add a URL parameter (or modify if already exists)_x000D_
* @param {string} url _x000D_
* @param {string} param the key to set_x000D_
* @param {string} value _x000D_
*/_x000D_
var addOrReplaceParam = function(url, param, value) {_x000D_
param = encodeURIComponent(param);_x000D_
var r = "([&?]|&)" + param + "\\b(?:=(?:[^&#]*))*";_x000D_
var a = document.createElement('a');_x000D_
var regex = new RegExp(r);_x000D_
var str = param + (value ? "=" + encodeURIComponent(value) : ""); _x000D_
a.href = url;_x000D_
var q = a.search.replace(regex, "$1"+str);_x000D_
if (q === a.search) {_x000D_
a.search += (a.search ? "&" : "") + str;_x000D_
} else {_x000D_
a.search = q;_x000D_
}_x000D_
return a.href;_x000D_
}_x000D_
_x000D_
url = "http://www.example.com#hashme";_x000D_
newurl = addParam(url, "ciao", "1");_x000D_
alert(newurl);
_x000D_
And please note that parameters should be encoded before being appended in query string.
You can detect when window.print() is finished simply by putting it in another function
//function to call if you want to print
var onPrintFinished=function(printed){console.log("do something...");}
//print command
onPrintFinished(window.print());
tested in Firefox,Google chrome,IE
According to the latest doc you can do the following-
Add a day
moment().add(1, 'days').calendar();
Add Year
moment().add(1, 'years').calendar();
Add Month
moment().add(1, 'months').calendar();
In my case: I forgot to activate virtualenv
I installed "pip install example" in the wrong virtualenv
Using the std::bitset answers and convenience templates:
#include <iostream>
#include <bitset>
#include <climits>
template<typename T>
struct BinaryForm {
BinaryForm(const T& v) : _bs(v) {}
const std::bitset<sizeof(T)*CHAR_BIT> _bs;
};
template<typename T>
inline std::ostream& operator<<(std::ostream& os, const BinaryForm<T> bf) {
return os << bf._bs;
}
Using it like this:
auto c = 'A';
std::cout << "c: " << c << " binary: " << BinaryForm{c} << std::endl;
unsigned x = 1234;
std::cout << "x: " << x << " binary: " << BinaryForm{x} << std::endl;
int64_t z { -1024 };
std::cout << "z: " << << " binary: " << BinaryForm{z} << std::endl;
Generates output:
c: A binary: 01000001
x: 1234 binary: 00000000000000000000010011010010
z: -1024 binary: 1111111111111111111111111111111111111111111111111111110000000000
Just used the Nathan's solution and it works fine. I needed to convert ISO-8859-1 to Unicode:
string isocontent = Encoding.GetEncoding("ISO-8859-1").GetString(fileContent, 0, fileContent.Length);
byte[] isobytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(isocontent);
byte[] ubytes = Encoding.Convert(Encoding.GetEncoding("ISO-8859-1"), Encoding.Unicode, isobytes);
return Encoding.Unicode.GetString(ubytes, 0, ubytes.Length);
If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40)
.
If you use pyplot
programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40)
or afterwards with ax.yaxis.label.set_size(40)
.
You can just use .animate()
the scrollTop
property, like this:
$("html, body").animate({ scrollTop: "300px" });
This behavior is explicitly documented in String.split(String regex)
(emphasis mine):
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
If you want those trailing empty strings included, you need to use String.split(String regex, int limit)
with a negative value for the second parameter (limit
):
String[] array = values.split("\\|", -1);
I have this issue too. I suspect there is an issue with DigitalOcean’s nameservers, so this will likely affect a lot of other people too. Here’s what I’ve done to temporarily get around it - but someone else might be able to advise on a better long-term fix:
Make sure your DNS Resolver config file is writable:
sudo chmod o+r /etc/resolv.conf
Temporarily change your DNS to use Google’s nameservers instead of DigitalOcean’s:
sudo nano /etc/resolv.conf
Change the IP address in the file to: 8.8.8.8
Press CTRL
+
X
to save the file.
This is only a temporary fix as this file is automatically written/updated by the server, however, I’ve not yet worked out what writes to it so that I can update it permanently.
The apostrophe character can be inserted by calling the CHAR function with the apostrophe's ASCII table lookup value, 39. The string values can then be concatenated together with a concatenate operator.
Insert into Person
(First, Last)
Values
'Joe',
concat('O',char(39),'Brien')
Have you tried passing -funroll-loops -fprefetch-loop-arrays
to GCC?
I get the following results with these additional optimizations:
[1829] /tmp/so_25078285 $ cat /proc/cpuinfo |grep CPU|head -n1
model name : Intel(R) Core(TM) i3-3225 CPU @ 3.30GHz
[1829] /tmp/so_25078285 $ g++ --version|head -n1
g++ (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3
[1829] /tmp/so_25078285 $ g++ -O3 -march=native -std=c++11 test.cpp -o test_o3
[1829] /tmp/so_25078285 $ g++ -O3 -march=native -funroll-loops -fprefetch-loop-arrays -std=c++11 test.cpp -o test_o3_unroll_loops__and__prefetch_loop_arrays
[1829] /tmp/so_25078285 $ ./test_o3 1
unsigned 41959360000 0.595 sec 17.6231 GB/s
uint64_t 41959360000 0.898626 sec 11.6687 GB/s
[1829] /tmp/so_25078285 $ ./test_o3_unroll_loops__and__prefetch_loop_arrays 1
unsigned 41959360000 0.618222 sec 16.9612 GB/s
uint64_t 41959360000 0.407304 sec 25.7443 GB/s
Your code works, but the fadeIn
doesn't, because it's already visible. I think the effect you want to achieve is: fadeOut
→ load
→ fadeIn
:
var auto_refresh = setInterval(function () {
$('.View').fadeOut('slow', function() {
$(this).load('/echo/json/', function() {
$(this).fadeIn('slow');
});
});
}, 15000); // refresh every 15000 milliseconds
Try it here: http://jsfiddle.net/kelunik/3qfNn/1/
Additional notice: As Khanh TO mentioned, you may need to get rid of the browser's internal cache. You can do so using $.ajax
and $.ajaxSetup ({ cache: false });
or the random-hack, he mentioned.
I believe the id accessors don't match the bean naming conventions and that's why the exception is thrown. They should be as follows:
public Integer getId() { return id; }
public void setId(Integer i){ id= i; }
Maps are not ordered, so there is no such thing as 'the first entry', and that's also why there is no get-by-index method on Map
(or HashMap
).
You could do this:
Map<String, String> map = ...; // wherever you get this from
// Get the first entry that the iterator returns
Map.Entry<String, String> entry = map.entrySet().iterator().next();
(Note: Checking for an empty map omitted).
Your code doesn't get all the entries in the map, it returns immediately (and breaks out of the loop) with the first entry that's found.
To print the key and value of this first element:
System.out.println("Key: "+entry.getKey()+", Value: "+entry.getValue());
Note: Calling iterator()
does not mean that you are iterating over the whole map.
Both are pretty similar. The real main difference between the two is that in the res
directory each file is given a pre-compiled ID
which can be accessed easily through R.id.[res id]
. This is useful to quickly and easily access images, sounds, icons...
The assets
directory is more like a filesystem and provides more freedom to put any file you would like in there. You then can access each of the files in that system as you would when accessing any file in any file system through Java. This directory is good for things such as game details, dictionaries,...etc. Hope that helps.
import java.lang.String;
This is an unnecessary import. java.lang classes are always implicitly imported. This means that you do not have to import them manually (explicitly).
HTTP status code 500 usually means that the webserver code has crashed. You need to determine the status code beforehand using HttpURLConnection#getResponseCode()
and in case of errors, read the HttpURLConnection#getErrorStream()
instead. It may namely contain information about the problem.
If the host has blocked you, you would rather have gotten a 4nn status code like 401 or 403.
A simple test to check whether a language supports pass-by-reference is simply writing a traditional swap. Can you write a traditional swap(a,b) method/function in Java?
A traditional swap method or function takes two arguments and swaps them such that variables passed into the function are changed outside the function. Its basic structure looks like
(Non-Java) Basic swap function structure
swap(Type arg1, Type arg2) {
Type temp = arg1;
arg1 = arg2;
arg2 = temp;
}
If you can write such a method/function in your language such that calling
Type var1 = ...;
Type var2 = ...;
swap(var1,var2);
actually switches the values of the variables var1 and var2, the language supports pass-by-reference. But Java does not allow such a thing as it supports passing the values only and not pointers or references.
Gotta love list comprehensions.
[dict([a, int(x)] for a, x in b.items()) for b in list]
(remark: for Python 2 only code you may use "iteritems" instead of "items")
The answer is:
gcc --version
Rather than searching on forums, for any possible option you can always type:
gcc --help
haha! :)
I faced the same issue. I think @Rishit answer helped me. This issue is related to 32 bit/ 64 bit version of driver. I was trying to read .xlsx files to SQL Server tables using SSIS
-(IBAction)Method
{
UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
[panRecognizer setMinimumNumberOfTouches:1];
[panRecognizer setMaximumNumberOfTouches:1];
[ViewMain addGestureRecognizer:panRecognizer];
[panRecognizer release];
}
- (Void)handlePan:(UIPanGestureRecognizer *)recognizer
{
CGPoint translation = [recognizer translationInView:self.view];
recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
if (recognizer.state == UIGestureRecognizerStateEnded) {
CGPoint velocity = [recognizer velocityInView:self.view];
CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
CGFloat slideMult = magnitude / 200;
NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult);
float slideFactor = 0.1 * slideMult; // Increase for more of a slide
CGPoint finalPoint = CGPointMake(recognizer.view.center.x + (velocity.x * slideFactor),
recognizer.view.center.y + (velocity.y * slideFactor));
finalPoint.x = MIN(MAX(finalPoint.x, 0), self.view.bounds.size.width);
finalPoint.y = MIN(MAX(finalPoint.y, 0), self.view.bounds.size.height);
[UIView animateWithDuration:slideFactor*2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
recognizer.view.center = finalPoint;
} completion:nil];
}
}
if you don't export default in A, B, C but just export {} then it's possible to do so
// things/A.js
export function A() {}
// things/B.js
export function B() {}
// things/C.js
export function C() {}
// foo.js
import * as Foo from ./thing
Foo.A()
Foo.B()
Foo.C()
There are two cases in which this error is raised.
You can use function: wc_get_page_id( 'cart' ) to get the ID of the page. This function will use the page setup as 'cart' page and not the slug. Meaning it will keep working also when you setup a different url for your 'cart' on the settings page. This works for all kind of Woocommerce special page, like 'checkout', 'shop' etc.
example:
if (wc_get_page_id( 'cart' ) == get_the_ID()) {
// Do something.
}
Join on one-to-many relation in JPQL looks as follows:
select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName
When several properties are specified in select
clause, result is returned as Object[]
:
Object[] temp = (Object[]) em.createNamedQuery("...")
.setParameter("groupName", groupName)
.getSingleResult();
String fname = (String) temp[0];
String lname = (String) temp[1];
By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table
to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:
@Entity @Table(name = "Users")
public class User implements Serializable { ... }
The MySQL extension:
Since it is deprecated, using it makes your code less future proof.
Lack of support for prepared statements is particularly important as they provide a clearer, less error-prone method of escaping and quoting external data than manually escaping it with a separate function call.
You can use following format:
<connectionStrings>
<add name="ConStringBDName" connectionString="Data Source=serverpath;Initial Catalog=YourDataBaseName;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
Most probably you will fing connectionstring tag in web.config after <appSettings>
Try out this.
php 5.5 has an imagecrop function http://php.net/manual/en/function.imagecrop.php
^CTR
or
^CTR.*
edit:
To be more clear: ^CTR
will match start of line and those chars. If all you want to do is match for a line itself (and already have the line to use), then that is all you really need. But if this is the case, you may be better off using a prefab substr()
type function. I don't know, what language are you are using. But if you are trying to match and grab the line, you will need something like .*
or .*$
or whatever, depending on what language/regex function you are using.
Javascript will be required; for example:
$(function(){
$('[type="date"]').prop('max', function(){
return new Date().toJSON().split('T')[0];
});
});
I had this issue when running ng test
, so to fix it, I added to my xyz.component.spec.ts
file:
import { MatTableModule } from '@angular/material';
And added it to imports
section in TestBed.configureTestingModule({})
:
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ ReactiveFormsModule, HttpClientModule, RouterTestingModule, MatTableModule ],
declarations: [ BookComponent ],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
.compileComponents();
}));
localStorage
is something that is kept on the client side. There is no data transmitted to the server side.
You can only get the data with JavaScript and you can send it to the server side with Ajax.
A generic solution that doesn't limit you to "this image" and "that image" only may be to add the 'onmouseover' and 'onmouseout' tags to the HTML code itself.
HTML
<img src="img1.jpg" onmouseover="swap('img2.jpg')" onmouseout="swap('img1.jpg')" />
JavaScript
function swap(newImg){
this.src = newImg;
}
Depending on your setup, maybe something like this would work better (and requires less HTML modification).
HTML
<img src="img1.jpg" id="ref1" />
<img src="img3.jpg" id="ref2" />
<img src="img5.jpg" id="ref3" />
JavaScript / jQuery
// Declare Arrays
imgList = new Array();
imgList["ref1"] = new Array();
imgList["ref2"] = new Array();
imgList["ref3"] = new Array();
//Set values for each mouse state
imgList["ref1"]["out"] = "img1.jpg";
imgList["ref1"]["over"] = "img2.jpg";
imgList["ref2"]["out"] = "img3.jpg";
imgList["ref2"]["over"] = "img4.jpg";
imgList["ref3"]["out"] = "img5.jpg";
imgList["ref3"]["over"] = "img6.jpg";
//Add the swapping functions
$("img").mouseover(function(){
$(this).attr("src", imgList[ $(this).attr("id") ]["over"]);
}
$("img").mouseout(function(){
$(this).attr("src", imgList[ $(this).attr("id") ]["out"]);
}