Didn't exactly get your intent. Do check Apache Commons configuration library http://commons.apache.org/configuration/
You can have multiple values against a key as in
key=value1,value2
and you can read this into an array as configuration.getAsStringArray("key")
To change only "background" (add corners, change color, ....) you can put it into FrameLayout with wanted background drawable, else you need to make nine patch background for to not lose spinner arrow. Spinner background is transparent.
Catch a Breakpoint somewhere.
Enter po NSHomeDirectory()
in console window
(lldb) po NSHomeDirectory() /Users/usernam/Library/Developer/CoreSimulator/Devices/4734F8C7-B90F-4566-8E89-5060505E387F/data/Containers/Data/Application/395818BB-6D0F-499F-AAFE-068A783D9753
use Object is great too.
var a=123
var b=234
var temp = {"a":a,"b":b}
console.log(temp["a"],temp["b"]);
Updating the ulimit worked for my Kosaraju's SCC implementation by fixing the segfault on both Python (Python segfault.. who knew!) and C++ implementations.
For my MAC, I found out the possible maximum via :
$ ulimit -s -H
65532
This is my solution. When Set-Location fails it throws a non-terminating error which is not seen by the catch block. Adding -ErrorAction Stop is the easiest way around this.
try {
Set-Location "$YourPath" -ErrorAction Stop;
} catch {
Write-Host "Exception has been caught";
}
editText.setInputType(InputType.TYPE_NULL);
<IfModule mod_expires.c>
# Enable expirations
ExpiresActive On
# Default directive
ExpiresDefault "access plus 1 month"
# My favicon
ExpiresByType image/x-icon "access plus 1 year"
# Images
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
# CSS
ExpiresByType text/css "access plus 1 month"
# Javascript
ExpiresByType application/javascript "access plus 1 year"
</IfModule>
In my particular case, I had a similar error on a legacy website used in my organization. To solve the issue, I had to list the website a a "Trusted site".
To do so:
I'm leaving this here in the remote case it will help someone.
Set the property RetainSameConnection
on the Connection Manager
to True
so that temporary table created in one Control Flow task can be retained in another task.
Here is a sample SSIS package written in SSIS 2008 R2
that illustrates using temporary tables.
Create a stored procedure that will create a temporary table named ##tmpStateProvince
and populate with few records. The sample SSIS package will first call the stored procedure and then will fetch the temporary table data to populate the records into another database table. The sample package will use the database named Sora
Use the below create stored procedure script.
USE Sora;
GO
CREATE PROCEDURE dbo.PopulateTempTable
AS
BEGIN
SET NOCOUNT ON;
IF OBJECT_ID('TempDB..##tmpStateProvince') IS NOT NULL
DROP TABLE ##tmpStateProvince;
CREATE TABLE ##tmpStateProvince
(
CountryCode nvarchar(3) NOT NULL
, StateCode nvarchar(3) NOT NULL
, Name nvarchar(30) NOT NULL
);
INSERT INTO ##tmpStateProvince
(CountryCode, StateCode, Name)
VALUES
('CA', 'AB', 'Alberta'),
('US', 'CA', 'California'),
('DE', 'HH', 'Hamburg'),
('FR', '86', 'Vienne'),
('AU', 'SA', 'South Australia'),
('VI', 'VI', 'Virgin Islands');
END
GO
Create a table named dbo.StateProvince
that will be used as the destination table to populate the records from temporary table. Use the below create table script to create the destination table.
USE Sora;
GO
CREATE TABLE dbo.StateProvince
(
StateProvinceID int IDENTITY(1,1) NOT NULL
, CountryCode nvarchar(3) NOT NULL
, StateCode nvarchar(3) NOT NULL
, Name nvarchar(30) NOT NULL
CONSTRAINT [PK_StateProvinceID] PRIMARY KEY CLUSTERED
([StateProvinceID] ASC)
) ON [PRIMARY];
GO
Create an SSIS package using Business Intelligence Development Studio (BIDS)
. Right-click on the Connection Managers tab at the bottom of the package and click New OLE DB Connection...
to create a new connection to access SQL Server 2008 R2 database.
Click New...
on Configure OLE DB Connection Manager.
Perform the following actions on the Connection Manager dialog.
Native OLE DB\SQL Server Native Client 10.0
from Provider since the package will connect to SQL Server 2008 R2 databaseMACHINENAME\INSTANCE
Use Windows Authentication
from Log on to the server section or whichever you prefer.Select or enter a database name
, the sample uses the database name Sora
.Test Connection
OK
on the Test connection succeeded message.OK
on Connection ManagerThe newly created data connection will appear on Configure OLE DB Connection Manager. Click OK
.
OLE DB connection manager KIWI\SQLSERVER2008R2.Sora
will appear under the Connection Manager tab at the bottom of the package. Right-click the connection manager and click Properties
Set the property RetainSameConnection
on the connection KIWI\SQLSERVER2008R2.Sora
to the value True
.
Right-click anywhere inside the package and then click Variables
to view the variables pane. Create the following variables.
A new variable named PopulateTempTable
of data type String
in the package scope SO_5631010
and set the variable with the value EXEC dbo.PopulateTempTable
.
A new variable named FetchTempData
of data type String
in the package scope SO_5631010
and set the variable with the value SELECT CountryCode, StateCode, Name FROM ##tmpStateProvince
Drag and drop an Execute SQL Task
on to the Control Flow tab. Double-click the Execute SQL Task to view the Execute SQL Task Editor.
On the General
page of the Execute SQL Task Editor, perform the following actions.
Create and populate temp table
OLE DB
KIWI\SQLSERVER2008R2.Sora
Variable
from SQLSourceTypeUser::PopulateTempTable
from SourceVariableOK
Drag and drop a Data Flow Task
onto the Control Flow tab. Rename the Data Flow Task as Transfer temp data to database table
. Connect the green arrow from the Execute SQL Task to the Data Flow Task.
Double-click the Data Flow Task
to switch to Data Flow tab. Drag and drop an OLE DB Source
onto the Data Flow tab. Double-click OLE DB Source to view the OLE DB Source Editor.
On the Connection Manager
page of the OLE DB Source Editor, perform the following actions.
KIWI\SQLSERVER2008R2.Sora
from OLE DB Connection ManagerSQL command from variable
from Data access modeUser::FetchTempData
from Variable nameColumns
pageClicking Columns
page on OLE DB Source Editor will display the following error because the table ##tmpStateProvince
specified in the source command variable does not exist and SSIS is unable to read the column definition.
To fix the error, execute the statement EXEC dbo.PopulateTempTable
using SQL Server Management Studio (SSMS) on the database Sora
so that the stored procedure will create the temporary table. After executing the stored procedure, click Columns
page on OLE DB Source Editor, you will see the column information. Click OK
.
Drag and drop OLE DB Destination
onto the Data Flow tab. Connect the green arrow from OLE DB Source to OLE DB Destination. Double-click OLE DB Destination
to open OLE DB Destination Editor.
On the Connection Manager
page of the OLE DB Destination Editor, perform the following actions.
KIWI\SQLSERVER2008R2.Sora
from OLE DB Connection ManagerTable or view - fast load
from Data access mode[dbo].[StateProvince]
from Name of the table or the viewMappings
pageClick Mappings
page on the OLE DB Destination Editor would automatically map the columns if the input and output column names are same. Click OK
. Column StateProvinceID
does not have a matching input column and it is defined as an IDENTITY
column in database. Hence, no mapping is required.
Data Flow tab should look something like this after configuring all the components.
Click the OLE DB Source
on Data Flow tab and press F4 to view Properties
. Set the property ValidateExternalMetadata
to False so that SSIS would not try to check for the existence of the temporary table during validation phase of the package execution.
Execute the query select * from dbo.StateProvince
in the SQL Server Management Studio (SSMS) to find the number of rows in the table. It should be empty before executing the package.
Execute the package. Control Flow shows successful execution.
In Data Flow tab, you will notice that the package successfully processed 6 rows. The stored procedure created early in this posted inserted 6 rows into the temporary table.
Execute the query select * from dbo.StateProvince
in the SQL Server Management Studio (SSMS) to find the 6 rows successfully inserted into the table. The data should match with rows founds in the stored procedure.
The above example illustrated how to create and use temporary table within a package.
I'll throw jsTree into the ring, too. I've found it fairly adaptable to your particular situation. It's packed as a jQuery plugin.
It can run from a variety of data sources, but my favorite is a simple nested list, as described by @joe_coolish or here:
<ul>
<li>
Item 1
<ul>
<li>Item 1.1</li>
...
</ul>
</li>
...
</ul>
This structure fails gracefully into a static tree when JS is not available in the client, and is easy enough to read and understand from a coding perspective.
By the way, I've just found out this post: http://blogs.msdn.com/b/webtopics/archive/2010/03/19/iis-7-5-how-to-enable-iis-configuration-auditing.aspx it explains how to audit changes on IIS. For those who face similar problems I suggest to turn on auditing and later see why your site stopped working.
You can copy the HTML svg tag from the website, then paste the code on a new html file and rename the extension to svg. It worked for me. Hope it helps you.
That would be the %CD%
variable.
@echo off
echo %CD%
%CD%
returns the current directory the batch script is in.
global $woocommerce;
var_dump($woocommerce->customer->get_country());
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = new WC_product($cart_item['product_id']);
var_dump($product);
}
The proper solution to resolve this issue is by following the steps
. Update Visual studio if you have older version to 15.5.4 (Optional)
Remove all binding redirects from web.config
Add this to the csproj file:
<PropertyGroup> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType> </PropertyGroup>
Build.
In the bin folder, there should be a (WebAppName).dll.config
file.
It should have redirects in it. Copy these to the web.config
Remove the above snipped from the csproj file again
It should work
Write a function lensort to sort a list of strings based on length.
def lensort(a):
n = len(a)
for i in range(n):
for j in range(i+1,n):
if len(a[i]) > len(a[j]):
temp = a[i]
a[i] = a[j]
a[j] = temp
return a
print lensort(["hello","bye","good"])
Yes, running a 64-bit OS in VMWare is possible from a 32-bit OS if you have a 64 bit processor.
I have an old Intel Core 2 Duo with Windows XP Professional 2002 running on it, and I got it to work.
First of all, see if your CPU is capable of running a 64-bit OS. Search for 'Processor check for 64-bit compatibility' on the VMware site. Run the program.
If it says your processor is capable, restart your computer and go into the BIOS and see if you have 'Virtualization' and are able to enable it. I was able to and got Windows Server 2008 R2 running under VMware on this old laptop.
I hope it works for you!
Use sqlcmd instead of osql if it's a 2005 database
You can use this class : TouchImageView
The schema definition for an attribute determines whether an attribute must have a value. If the manager
attribute in the example given is the attribute defined in RFC4524 with OID 0.9.2342.19200300.100.1.10
, then that attribute has DN syntax. DN syntax is a sequence of relative distinguished names and must not be empty. The filter given in the example is used to cause the LDAP directory server to return only entries that do not have a manager
attribute to the LDAP client in the search result.
See https://gist.github.com/nathanosoares/6234e9b06608595e018ca56c7b3d5a57
public static void main(String[] args) {
RandomList<String> set = new RandomList<>();
set.add("a", 10);
set.add("b", 10);
set.add("c", 30);
set.add("d", 300);
set.forEach((t) -> {
System.out.println(t.getChance());
});
HashMap<String, Integer> count = new HashMap<>();
IntStream.range(0, 100).forEach((value) -> {
String str = set.raffle();
count.put(str, count.getOrDefault(str, 0) + 1);
});
count.entrySet().stream().forEach(entry -> {
System.out.println(String.format("%s: %s", entry.getKey(), entry.getValue()));
});
}
Output:
2.857142857142857
2.857142857142857
8.571428571428571
85.71428571428571
a: 2
b: 1
c: 9
d: 88
In addirion to the good answers here, specifically Robert Lujo's.
I want to say in my case I've been deliberately trying to statically compile a version of ffmpeg. All the required dependencies and what else heretofore required, I've done static compilation.
When I ran ./configure
for the ffmpeg process I didnt notice --enable-shared
was on the commandline. Removing it and running ./configure
is only then I was able to compile correctly (All 56 mbs of an ffmpeg binary). Check that out as well if your intention is static compilation
Another thing that can cause this error is creating a model with the centering/scaling standardize function from the arm package -- m <- standardize(lm(y ~ x, data = train))
If you then try predict(m)
, you get the same error as in this question.
For completeness - adding to accepted answer above - in case you are interested in any sibling regardless of the element type you can use variation:
following-sibling::*
import base64
print(base64.b64encode("password".encode("utf-8")))
print(base64.b64decode(b'cGFzc3dvcmQ='.decode("utf-8")))
Add this to AppServiceProvider.php
use Illuminate\Support\Facades\Schema;
public function boot() {
Schema::defaultStringLength(191);
}
Try converting your boolean to an integer?
echo (int)$bool_val;
You cannot get the exact code, but you can get a decompiled version of it.
The most popular (and best) tool is Reflector, but there are also other .Net decompilers (such as Dis#).
You can also decompile the IL using ILDASM, which comes bundled with the .Net Framework SDK Tools.
Another way is to let Eclipse do the import work for you. Hover your mouse over the com.google.android.gms
import that can not be resolved and towards the bottom of the popup menu, select the Fix project setup... option as below. Then it'll prompt to import the google play services library. Select that and you should be good to go.
Try this one::
import urllib2
website='https://www.allyourmusic.com'
try:
response = urllib2.urlopen(website)
if response.code==200:
print("site exists!")
else:
print("site doesn't exists!")
except urllib2.HTTPError, e:
print(e.code)
except urllib2.URLError, e:
print(e.args)
If GPL is fine you may have an additional look at jPodRenderer (SourceForge)
A good explanation of how BFS computes shortest paths, accompanied by the most efficient simple BFS algorithm of which I'm aware and also by working code, is provided in the following peer-reviewed paper:
https://queue.acm.org/detail.cfm?id=3424304
The paper explains how BFS computes a shortest-paths tree represented by per-vertex parent pointers, and how to recover a particular shortest path between any two vertices from the parent pointers. The explanation of BFS takes three forms: prose, pseudocode, and a working C program.
The paper also describes "Efficient BFS" (E-BFS), a simple variant of classic textbook BFS that improves its efficiency. In the asymptotic analysis, running time improves from Theta(V+E) to Omega(V). In words: classic BFS always runs in time proportional to the number of vertices plus the number of edges, whereas E-BFS sometimes runs in time proportional to the number of vertices alone, which can be much smaller. In practice E-BFS can be much faster, depending on the input graph. E-BFS sometimes offers no advantage over classic BFS but it's never much slower.
Remarkably, despites its simplicity E-BFS appears not to be widely known.
$matches = array();
preg_match('/id=([0-9]+)\?/', $url, $matches);
This is safe for if the format changes. slandau's answer won't work if you ever have any other numbers in the URL.
I have run into this issue before and found that sometimes padding is the issue.
By removing padding from the ul, any li's set to inline-block will be nicely centred:
* {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
ul {_x000D_
width: 120px;_x000D_
margin: auto;_x000D_
text-align: center;_x000D_
border: 1px solid black;_x000D_
}_x000D_
_x000D_
li {_x000D_
display: inline-block;_x000D_
}_x000D_
_x000D_
ul.no_pad {_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
p {_x000D_
margin: auto;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.break {_x000D_
margin: 50px 10px;_x000D_
}
_x000D_
<div> _x000D_
<p>With Padding (Default Style)</p>_x000D_
<ul class="with_pad">_x000D_
<li>x</li>_x000D_
<li>x</li>_x000D_
<li>x</li>_x000D_
<li>x</li>_x000D_
</ul>_x000D_
<div class="break"></div>_x000D_
<p>No Padding (Padding: 0)</p>_x000D_
<ul class="no_pad">_x000D_
<li>x</li>_x000D_
<li>x</li>_x000D_
<li>x</li>_x000D_
<li>x</li>_x000D_
</ul>_x000D_
<div>
_x000D_
Hope that helps anyone running into this same issue :)
Cheers,
Jake
Async arrow functions look like this:
const foo = async () => {
// do something
}
Async arrow functions look like this for a single argument passed to it:
const foo = async evt => {
// do something with evt
}
Async arrow functions look like this for multiple arguments passed to it:
const foo = async (evt, callback) => {
// do something with evt
// return response with callback
}
The anonymous form works as well:
const foo = async function() {
// do something
}
An async function declaration looks like this:
async function foo() {
// do something
}
Using async function in a callback:
const foo = event.onCall(async () => {
// do something
})
// plugins/moment.js
import moment from 'moment';
moment.locale('ru');
export default function install (Vue) {
Object.defineProperties(Vue.prototype, {
$moment: {
get () {
return moment;
}
}
})
}
// main.js
import moment from './plugins/moment.js';
Vue.use(moment);
// use this.$moment in your components
I know this question is about Linux, but in case someone stumbles on this problem on Mac like I did here is the solution for that. I had the exact same problem on Mac because ffmpeg
is not installed by default apparently, and so I could solve it using:
brew install yasm
brew install ffmpeg
I use setTimeout.
Apparently the difference is setTimeout calls the method once, setInterval calls it repeatdly.
Here is a good article explaining the difference: Tutorial: JavaScript timers with setTimeout and setInterval
The best way to set radiobuttons state in jquery:
HTML:
<input type="radio" name="color" value="orange" /> Orange
<input type="radio" name="color" value="pink" /> Pink
<input type="radio" name="color" value="black" /> Black
<input type="radio" name="color" value="pinkish purple" /> Pinkish Purple
Jquery (1.4+) code to pre-select one button :
var presetValue = "black";
$("[name=color]").filter("[value='"+presetValue+"']").attr("checked","checked");
In Jquery 1.6+ code the .prop() method is preferred :
var presetValue = "black";
$("[name=color]").filter("[value='"+presetValue+"']").prop("checked",true);
To unselect the buttons :
$("[name=color]").removeAttr("checked");
In case anybody has an issue with setting datetimepicker control to blank during the form load event, and then show the current date as needed, here is an example:
MAKE SURE THAT CustomFormat = " "
has same number of spaces (at least one space) in both methods
Private Sub setDateTimePickerBlank(ByVal dateTimePicker As DateTimePicker)
dateTimePicker.Visible = True
dateTimePicker.Format = DateTimePickerFormat.Custom
dateTimePicker.CustomFormat = " "
End Sub
Private Sub dateTimePicker_MouseHover(ByVal sender As Object, ByVal e As
System.EventArgs) Handles dateTimePicker.MouseHover
Dim dateTimePicker As DateTimePicker = CType(sender, DateTimePicker)
If dateTimePicker.Text = " " Then
dateTimePicker.Text = Format(DateTime.Now, "MM/dd/yyyy")
End If
End Sub
I had the same problem. java.net.UnknownHostException: Unable to resolve host “”...
I'm running Visual Studio 2019 and Xamarin.
I also switched back to my WiFi but was on a hot spot.
I solved this by clean swiping the emulator. Restore to factory settings. Then re-running visual studio xamarin app which wil redeploy your app again to the fresh emulator.
It worked. I thought I was going to battle for days to solve this. Luckily this post pointed me in the right direction.
I could not understand how it worked perfectly before and then stopped with no code change.
This is my code for reference:
using var response = await httpClient.GetAsync(sb.ToString());
string apiResponse = await response.Content.ReadAsStringAsync();
So i have been struggling too on the same issue. The quick and easiest way to solve the problem is by just adding
modal-lg
on your modal DivExample <div class="modal-dialog modal-lg">
I've faced this issue and the solution was making sure that all the data from the child field are matching the parent field
for example, you want to add foreign key inside (attendance) table to the column (employeeName)
where the parent is (employees) table, (employeeName) column
all the data in attendance.employeeName must be matching employee.employeeName
I found the simplest way:
gnome-terminal --tab -e 'command 1' --tab -e 'command 2'
I use tmux
instead of using terminal directly. So what I want is really a single and simple command/shell file to build the development env
with several tmux
windows. The shell code is as below:
#!/bin/bash
tabs="adb ana repo"
gen_params() {
local params=""
for tab in ${tabs}
do
params="${params} --tab -e 'tmux -u attach-session -t ${tab}'"
done
echo "${params}"
}
cmd="gnome-terminal $(gen_params)"
eval $cmd
You can simply do this:
user.js
class User {
//...
}
module.exports = User
server.js
const User = require('./user.js')
// Instantiate User:
let user = new User()
This is called CommonJS module.
Sometimes it could be useful to export more than one value. For example it could be classes, functions or constants. This is an alternative version of the same functionality:
user.js
class User {}
exports.User = User // Spot the difference
server.js
const {User} = require('./user.js') // Destructure on import
// Instantiate User:
let user = new User()
Since Node.js version 14 it's possible to use ES Modules with CommonJS. Read more about it in the ESM documentation.
?? Don't use globals, it creates potential conflicts with the future code.
a simpler solution based on this answer:
public static String prettyFormat(String input, int indent) {
try {
Source xmlInput = new StreamSource(new StringReader(input));
StringWriter stringWriter = new StringWriter();
StreamResult xmlOutput = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", indent);
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(xmlInput, xmlOutput);
return xmlOutput.getWriter().toString();
} catch (Exception e) {
throw new RuntimeException(e); // simple exception handling, please review it
}
}
public static String prettyFormat(String input) {
return prettyFormat(input, 2);
}
testcase:
prettyFormat("<root><child>aaa</child><child/></root>");
returns:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<child>aaa</child>
<child/>
</root>
It's an efficiency question. LinkedList
is fast for adding and deleting elements, but slow to access a specific element. ArrayList
is fast for accessing a specific element but can be slow to add to either end, and especially slow to delete in the middle.
Array vs ArrayList vs LinkedList vs Vector goes more in depth, as does Linked List.
To read multiple sheets from a workbook, use readxl package as follows:
library(readxl)
library(dplyr)
final_dataFrame <- bind_rows(path_to_workbook %>%
excel_sheets() %>%
set_names() %>%
map(read_excel, path = path_to_workbook))
Here, bind_rows (dplyr
) will put all data rows from all sheets
into one data frame, and path_to_workbook
is the location of your data: "dir/of/the/data/workbook".
function in_arrayi($needle, $haystack) {
return in_array(strtolower($needle), array_map('strtolower', $haystack));
}
From Documentation
If someone is having issues with creating tables by using files dedicated to each model, be aware of running the "create_all" function from a file different from the one where that function is declared. So, if the filesystem is like this:
Root
--app.py <-- file from which app will be run
--models
----user.py <-- file with "User" model
----order.py <-- file with "Order" model
----database.py <-- file with database and "create_all" function declaration
Be careful about calling the "create_all" function from app.py.
This concept is explained better by the answer to this thread posted by @SuperShoot
route -f causes damage. So we need to either disconnect the correct parts of the routing table or find out how to rebuild it.
To keep beginner attitude you can explain that all the command line is automaticaly splite in a array fo String (the String[]
).
For static
you have to explain, that it not a field like another : it is unique in the JVM even if you have thousand instances of the class
So main
is static, because it is the only way to find it (linked in its own class) in a jar
.
... after you look at coding, and your job begin ...
Have you tried:
ifconfig 10:35978f0 down
As the physical interface is 10
and the virtual aspect is after the colon :
.
See also https://www.cyberciti.biz/faq/linux-command-to-remove-virtual-interfaces-or-network-aliases/
-Confirm
is a switch in most PowerShell cmdlets that forces the cmdlet to ask for user confirmation. What you're actually looking for is the Read-Host
cmdlet:
$confirmation = Read-Host "Are you Sure You Want To Proceed:"
if ($confirmation -eq 'y') {
# proceed
}
or the PromptForChoice()
method of the host user interface:
$title = 'something'
$question = 'Are you sure you want to proceed?'
$choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription]
$choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes'))
$choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&No'))
$decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
if ($decision -eq 0) {
Write-Host 'confirmed'
} else {
Write-Host 'cancelled'
}
Edit:
As M-pixel pointed out in the comments the code could be simplified further, because the choices can be passed as a simple string array.
$title = 'something'
$question = 'Are you sure you want to proceed?'
$choices = '&Yes', '&No'
$decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
if ($decision -eq 0) {
Write-Host 'confirmed'
} else {
Write-Host 'cancelled'
}
The database must have a name (example DB1), try this one:
OracleConnection con = new OracleConnection("data source=DB1;user id=fastecit;password=fastecit");
In case the TNS is not defined you can also try this one:
OracleConnection con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=DB1)));
User Id=fastecit;Password=fastecit");
You can use LINQ to achieve that too:
var exists = array.ElementAtOrDefault(index) != null;
If you are Using HTML5 you can add the attribute 'download' to your links.
<a href="/test.pdf" download>
Private Constructors can be defnied in the Java for the following reasons
To have control on the instantiation of the Java objects, it wont allow you to create an instance of an object.
It wont allow the class to be Subclassed
This has a special advantage when implementing the singleton Pattern, Private contstructors are used for it and have a control on the creating the instance for the whole application.
when you want to have a class with all constants defined and Does not require its instance any more, then we declare that class as a private constructor.
For those interested, this is code for creating SHA-256 hash using sjcl
:
import sjcl from 'sjcl'
const myString = 'Hello'
const myBitArray = sjcl.hash.sha256.hash(myString)
const myHash = sjcl.codec.hex.fromBits(myBitArray)
just you pass this things in your select query. using CASE
CASE WHEN gender=0 then 'Female' WHEN gender=1 then 'Male' END as Genderdisp
Scato wrotes:
anything you want to use for bitwise operations must be between 0x80000000 (-2147483648 or -2^31) and 0x7fffffff (2147483647 or 2^31 - 1).
the console will tell you that 0x80000000 equals +2147483648, but 0x80000000 & 0x80000000 equals -2147483648
Hex-Decimals are unsigned positive values, so 0x80000000 = 2147483648 - thats mathematically correct. If you want to make it a signed value you have to right shift: 0x80000000 >> 0 = -2147483648. You can write 1 << 31 instead, too.
We do it differently. IMHO we do it in an easier way: in master
we are working on the next major version.
Each larger feature gets its own branch (derived from master) and will be rebased (+ force pushed) on top of master regularly by the developer. Rebasing only works fine if a single developer works on this feature. If the feature is finished, it will be freshly rebased onto master and then the master fast-forwarded to the latest feature commit.
To avoid the rebasing/forced push one also can merge master changes regularly to the feature branch and if it's finished merge the feature branch into master (normal merge or squash merge). But IMHO this makes the feature branch less clear and makes it much more difficult to reorder/cleanup the commits.
If a new release is coming, we create a side-branch out of master, e.g. release-5
where only bugs get fixed.
You can set the output of System.out programmatically by doing:
System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream("/location/to/console.out")), true));
Edit:
Due to the fact that this solution is based on a PrintStream
, we can enable autoFlush, but according to the docs:
autoFlush - A boolean; if true, the output buffer will be flushed whenever a byte array is written, one of the println methods is invoked, or a newline character or byte ('\n') is written
So if a new line isn't written, remember to System.out.flush()
manually.
(Thanks Robert Tupelo-Schneck)
You can simply truncate the table to reset the sequence
TRUNCATE TABLE TABLE_NAME
R defines a ~
(tilde) operator for use in formulas. Formulas have all sorts of uses, but perhaps the most common is for regression:
library(datasets)
lm( myFormula, data=iris)
help("~")
or help("formula")
will teach you more.
@Spacedman has covered the basics. Let's discuss how it works.
First, being an operator, note that it is essentially a shortcut to a function (with two arguments):
> `~`(lhs,rhs)
lhs ~ rhs
> lhs ~ rhs
lhs ~ rhs
That can be helpful to know for use in e.g. apply
family commands.
Second, you can manipulate the formula as text:
oldform <- as.character(myFormula) # Get components
myFormula <- as.formula( paste( oldform[2], "Sepal.Length", sep="~" ) )
Third, you can manipulate it as a list:
myFormula[[2]]
myFormula[[3]]
Finally, there are some helpful tricks with formulae (see help("formula")
for more):
myFormula <- Species ~ .
For example, the version above is the same as the original version, since the dot means "all variables not yet used." This looks at the data.frame you use in your eventual model call, sees which variables exist in the data.frame but aren't explicitly mentioned in your formula, and replaces the dot with those missing variables.
Use %0D%0A
for a line break in your body
Example (Demo):
<a href="mailto:[email protected]?subject=Suggestions&body=name:%0D%0Aemail:">test</a>?
^^^^^^
Writing from phone, but curvycorners is really good, since it adds it's own borders only if browser doesn't support it by default. In other words, browsers which already support some CSS3 will use their own system to provide corners.
https://code.google.com/p/curvycorners/
This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode
, which was only introduced in JPA 2.0.
Since you use Maven, do mvn dependency:tree
, find the artifact:
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
And remove it from your setup. (See Excluding Dependencies)
AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:
System.out.println(EntityManager.class.getProtectionDomain()
.getCodeSource()
.getLocation());
See where that points you and get rid of that artifact.
Ahh, now I finally see the problem. Get rid of this:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jpa</artifactId>
<version>2.0.8</version>
</dependency>
and replace it with
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
On a different note, you should set all test libraries (spring-test, easymock etc.) to
<scope>test</scope>
Either document.getElementById('i1')
, document.getElementById('i2')
, or document.getElementsByName("username")[0]
is returning no element. Check, that all elements exist.
I am not sure if you have an old version of IntelliJ IDEA, but if I go to menu File ? Settings... ? Inspections ? Serialization issues ? Serializable class without 'serialVersionUID'` enabled, the class you provide give me warnings.
If I try the first class I see:
BTW: It didn't show me a warning until I added { }
to the end of each class to fix the compile error.
Something like this would work for reading:
String filename = "something.csv";
BufferedReader input = null;
List<List<String>> csvData = new ArrayList<List<String>>();
try
{
input = new BufferedReader(new FileReader(filename));
String line = null;
while (( line = input.readLine()) != null)
{
String[] data = line.split(",");
csvData.add(Arrays.toList(data));
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if(input != null)
{
input.close();
}
}
file_name=test.log
# set first K lines:
K=1000
# line count (N):
N=$(wc -l < $file_name)
# length of the bottom file:
L=$(( $N - $K ))
# create the top of file:
head -n $K $file_name > top_$file_name
# create bottom of file:
tail -n $L $file_name > bottom_$file_name
Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so
split -l 300000 file_name
will output xaa
with 300k lines and xab
with 100k lines, for an input with 400k lines.
The question is tagged WPF but the answers so far are specific WinForms and Win32.
To do this in WPF, simply construct a KeyEventArgs and call RaiseEvent on the target. For example, to send an Insert key KeyDown event to the currently focused element:
var key = Key.Insert; // Key to send
var target = Keyboard.FocusedElement; // Target element
var routedEvent = Keyboard.KeyDownEvent; // Event to send
target.RaiseEvent(
new KeyEventArgs(
Keyboard.PrimaryDevice,
PresentationSource.FromVisual(target),
0,
key)
{ RoutedEvent=routedEvent }
);
This solution doesn't rely on native calls or Windows internals and should be much more reliable than the others. It also allows you to simulate a keypress on a specific element.
Note that this code is only applicable to PreviewKeyDown, KeyDown, PreviewKeyUp, and KeyUp events. If you want to send TextInput events you'll do this instead:
var text = "Hello";
var target = Keyboard.FocusedElement;
var routedEvent = TextCompositionManager.TextInputEvent;
target.RaiseEvent(
new TextCompositionEventArgs(
InputManager.Current.PrimaryKeyboardDevice,
new TextComposition(InputManager.Current, target, text))
{ RoutedEvent = routedEvent }
);
Also note that:
Controls expect to receive Preview events, for example PreviewKeyDown should precede KeyDown
Using target.RaiseEvent(...) sends the event directly to the target without meta-processing such as accelerators, text composition and IME. This is normally what you want. On the other hand, if you really do what to simulate actual keyboard keys for some reason, you would use InputManager.ProcessInput() instead.
I just used:
import java.nio.file.Path;
import java.nio.file.Paths;
...
Path workingDirectory=Paths.get(".").toAbsolutePath();
Append ll suffix to hex digits for 64-bit (long long int), or ull suffix for unsigned 64-bit (unsigned long long)
You can use the timestamp
plugin of mongoose-troop
to add this behavior to any schema.
This is my edited version : you just need to add an extra argument "autoClose".
example :
$('input[name="fieldName"]').datepicker({ autoClose: true});
also you can specify a close callback if you want. :)
replace datepicker.js with this:
!function( $ ) {
// Picker object
var Datepicker = function(element, options , closeCallBack){
this.element = $(element);
this.format = DPGlobal.parseFormat(options.format||this.element.data('date-format')||'dd/mm/yyyy');
this.autoClose = options.autoClose||this.element.data('date-autoClose')|| true;
this.closeCallback = closeCallBack || function(){};
this.picker = $(DPGlobal.template)
.appendTo('body')
.on({
click: $.proxy(this.click, this)//,
//mousedown: $.proxy(this.mousedown, this)
});
this.isInput = this.element.is('input');
this.component = this.element.is('.date') ? this.element.find('.add-on') : false;
if (this.isInput) {
this.element.on({
focus: $.proxy(this.show, this),
//blur: $.proxy(this.hide, this),
keyup: $.proxy(this.update, this)
});
} else {
if (this.component){
this.component.on('click', $.proxy(this.show, this));
} else {
this.element.on('click', $.proxy(this.show, this));
}
}
this.minViewMode = options.minViewMode||this.element.data('date-minviewmode')||0;
if (typeof this.minViewMode === 'string') {
switch (this.minViewMode) {
case 'months':
this.minViewMode = 1;
break;
case 'years':
this.minViewMode = 2;
break;
default:
this.minViewMode = 0;
break;
}
}
this.viewMode = options.viewMode||this.element.data('date-viewmode')||0;
if (typeof this.viewMode === 'string') {
switch (this.viewMode) {
case 'months':
this.viewMode = 1;
break;
case 'years':
this.viewMode = 2;
break;
default:
this.viewMode = 0;
break;
}
}
this.startViewMode = this.viewMode;
this.weekStart = options.weekStart||this.element.data('date-weekstart')||0;
this.weekEnd = this.weekStart === 0 ? 6 : this.weekStart - 1;
this.onRender = options.onRender;
this.fillDow();
this.fillMonths();
this.update();
this.showMode();
};
Datepicker.prototype = {
constructor: Datepicker,
show: function(e) {
this.picker.show();
this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
this.place();
$(window).on('resize', $.proxy(this.place, this));
if (e ) {
e.stopPropagation();
e.preventDefault();
}
if (!this.isInput) {
}
var that = this;
$(document).on('mousedown', function(ev){
if ($(ev.target).closest('.datepicker').length == 0) {
that.hide();
}
});
this.element.trigger({
type: 'show',
date: this.date
});
},
hide: function(){
this.picker.hide();
$(window).off('resize', this.place);
this.viewMode = this.startViewMode;
this.showMode();
if (!this.isInput) {
$(document).off('mousedown', this.hide);
}
//this.set();
this.element.trigger({
type: 'hide',
date: this.date
});
},
set: function() {
var formated = DPGlobal.formatDate(this.date, this.format);
if (!this.isInput) {
if (this.component){
this.element.find('input').prop('value', formated);
}
this.element.data('date', formated);
} else {
this.element.prop('value', formated);
}
},
setValue: function(newDate) {
if (typeof newDate === 'string') {
this.date = DPGlobal.parseDate(newDate, this.format);
} else {
this.date = new Date(newDate);
}
this.set();
this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
this.fill();
},
place: function(){
var offset = this.component ? this.component.offset() : this.element.offset();
this.picker.css({
top: offset.top + this.height,
left: offset.left
});
},
update: function(newDate){
this.date = DPGlobal.parseDate(
typeof newDate === 'string' ? newDate : (this.isInput ? this.element.prop('value') : this.element.data('date')),
this.format
);
this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
this.fill();
},
fillDow: function(){
var dowCnt = this.weekStart;
var html = '<tr>';
while (dowCnt < this.weekStart + 7) {
html += '<th class="dow">'+DPGlobal.dates.daysMin[(dowCnt++)%7]+'</th>';
}
html += '</tr>';
this.picker.find('.datepicker-days thead').append(html);
},
fillMonths: function(){
var html = '';
var i = 0
while (i < 12) {
html += '<span class="month">'+DPGlobal.dates.monthsShort[i++]+'</span>';
}
this.picker.find('.datepicker-months td').append(html);
},
fill: function() {
var d = new Date(this.viewDate),
year = d.getFullYear(),
month = d.getMonth(),
currentDate = this.date.valueOf();
this.picker.find('.datepicker-days th:eq(1)')
.text(DPGlobal.dates.months[month]+' '+year);
var prevMonth = new Date(year, month-1, 28,0,0,0,0),
day = DPGlobal.getDaysInMonth(prevMonth.getFullYear(), prevMonth.getMonth());
prevMonth.setDate(day);
prevMonth.setDate(day - (prevMonth.getDay() - this.weekStart + 7)%7);
var nextMonth = new Date(prevMonth);
nextMonth.setDate(nextMonth.getDate() + 42);
nextMonth = nextMonth.valueOf();
var html = [];
var clsName,
prevY,
prevM;
while(prevMonth.valueOf() < nextMonth) {zs
if (prevMonth.getDay() === this.weekStart) {
html.push('<tr>');
}
clsName = this.onRender(prevMonth);
prevY = prevMonth.getFullYear();
prevM = prevMonth.getMonth();
if ((prevM < month && prevY === year) || prevY < year) {
clsName += ' old';
} else if ((prevM > month && prevY === year) || prevY > year) {
clsName += ' new';
}
if (prevMonth.valueOf() === currentDate) {
clsName += ' active';
}
html.push('<td class="day '+clsName+'">'+prevMonth.getDate() + '</td>');
if (prevMonth.getDay() === this.weekEnd) {
html.push('</tr>');
}
prevMonth.setDate(prevMonth.getDate()+1);
}
this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
var currentYear = this.date.getFullYear();
var months = this.picker.find('.datepicker-months')
.find('th:eq(1)')
.text(year)
.end()
.find('span').removeClass('active');
if (currentYear === year) {
months.eq(this.date.getMonth()).addClass('active');
}
html = '';
year = parseInt(year/10, 10) * 10;
var yearCont = this.picker.find('.datepicker-years')
.find('th:eq(1)')
.text(year + '-' + (year + 9))
.end()
.find('td');
year -= 1;
for (var i = -1; i < 11; i++) {
html += '<span class="year'+(i === -1 || i === 10 ? ' old' : '')+(currentYear === year ? ' active' : '')+'">'+year+'</span>';
year += 1;
}
yearCont.html(html);
},
click: function(e) {
e.stopPropagation();
e.preventDefault();
var target = $(e.target).closest('span, td, th');
if (target.length === 1) {
switch(target[0].nodeName.toLowerCase()) {
case 'th':
switch(target[0].className) {
case 'switch':
this.showMode(1);
break;
case 'prev':
case 'next':
this.viewDate['set'+DPGlobal.modes[this.viewMode].navFnc].call(
this.viewDate,
this.viewDate['get'+DPGlobal.modes[this.viewMode].navFnc].call(this.viewDate) +
DPGlobal.modes[this.viewMode].navStep * (target[0].className === 'prev' ? -1 : 1)
);
this.fill();
this.set();
break;
}
break;
case 'span':
if (target.is('.month')) {
var month = target.parent().find('span').index(target);
this.viewDate.setMonth(month);
} else {
var year = parseInt(target.text(), 10)||0;
this.viewDate.setFullYear(year);
}
if (this.viewMode !== 0) {
this.date = new Date(this.viewDate);
this.element.trigger({
type: 'changeDate',
date: this.date,
viewMode: DPGlobal.modes[this.viewMode].clsName
});
}
this.showMode(-1);
this.fill();
this.set();
break;
case 'td':
if (target.is('.day') && !target.is('.disabled')){
var day = parseInt(target.text(), 10)||1;
var month = this.viewDate.getMonth();
if (target.is('.old')) {
month -= 1;
} else if (target.is('.new')) {
month += 1;
}
var year = this.viewDate.getFullYear();
this.date = new Date(year, month, day,0,0,0,0);
this.viewDate = new Date(year, month, Math.min(28, day),0,0,0,0);
this.fill();
this.set();
this.element.trigger({
type: 'changeDate',
date: this.date,
viewMode: DPGlobal.modes[this.viewMode].clsName
});
if(this.autoClose === true){
this.hide();
this.closeCallback();
}
}
break;
}
}
},
mousedown: function(e){
e.stopPropagation();
e.preventDefault();
},
showMode: function(dir) {
if (dir) {
this.viewMode = Math.max(this.minViewMode, Math.min(2, this.viewMode + dir));
}
this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
}
};
$.fn.datepicker = function ( option, val ) {
return this.each(function () {
var $this = $(this);
var datePicker = $this.data('datepicker');
var options = typeof option === 'object' && option;
if (!datePicker) {
if (typeof val === 'function')
$this.data('datepicker', (datePicker = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options),val)));
else{
$this.data('datepicker', (datePicker = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options))));
}
}
if (typeof option === 'string') datePicker[option](val);
});
};
$.fn.datepicker.defaults = {
onRender: function(date) {
return '';
}
};
$.fn.datepicker.Constructor = Datepicker;
var DPGlobal = {
modes: [
{
clsName: 'days',
navFnc: 'Month',
navStep: 1
},
{
clsName: 'months',
navFnc: 'FullYear',
navStep: 1
},
{
clsName: 'years',
navFnc: 'FullYear',
navStep: 10
}],
dates:{
days: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"],
daysShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"],
daysMin: ["D", "L", "Ma", "Me", "J", "V", "S", "D"],
months: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"],
monthsShort: ["Jan", "Fév", "Mar", "Avr", "Mai", "Jui", "Jul", "Aou", "Sep", "Oct", "Nov", "Déc"],
today: "Aujourd'hui",
clear: "Effacer",
weekStart: 1,
format: "dd/mm/yyyy"
},
isLeapYear: function (year) {
return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0))
},
getDaysInMonth: function (year, month) {
return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
},
parseFormat: function(format){
var separator = format.match(/[.\/\-\s].*?/),
parts = format.split(/\W+/);
if (!separator || !parts || parts.length === 0){
throw new Error("Invalid date format.");
}
return {separator: separator, parts: parts};
},
parseDate: function(date, format) {
var parts = date.split(format.separator),
date = new Date(),
val;
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
if (parts.length === format.parts.length) {
var year = date.getFullYear(), day = date.getDate(), month = date.getMonth();
for (var i=0, cnt = format.parts.length; i < cnt; i++) {
val = parseInt(parts[i], 10)||1;
switch(format.parts[i]) {
case 'dd':
case 'd':
day = val;
date.setDate(val);
break;
case 'mm':
case 'm':
month = val - 1;
date.setMonth(val - 1);
break;
case 'yy':
year = 2000 + val;
date.setFullYear(2000 + val);
break;
case 'yyyy':
year = val;
date.setFullYear(val);
break;
}
}
date = new Date(year, month, day, 0 ,0 ,0);
}
return date;
},
formatDate: function(date, format){
var val = {
d: date.getDate(),
m: date.getMonth() + 1,
yy: date.getFullYear().toString().substring(2),
yyyy: date.getFullYear()
};
val.dd = (val.d < 10 ? '0' : '') + val.d;
val.mm = (val.m < 10 ? '0' : '') + val.m;
var date = [];
for (var i=0, cnt = format.parts.length; i < cnt; i++) {
date.push(val[format.parts[i]]);
}
return date.join(format.separator);
},
headTemplate: '<thead>'+
'<tr>'+
'<th class="prev">‹</th>'+
'<th colspan="5" class="switch"></th>'+
'<th class="next">›</th>'+
'</tr>'+
'</thead>',
contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>'
};
DPGlobal.template = '<div class="datepicker dropdown-menu">'+
'<div class="datepicker-days">'+
'<table class=" table-condensed">'+
DPGlobal.headTemplate+
'<tbody></tbody>'+
'</table>'+
'</div>'+
'<div class="datepicker-months">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
'</table>'+
'</div>'+
'<div class="datepicker-years">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
'</table>'+
'</div>'+
'</div>';
}( window.jQuery );
"Not Possible". You can use a function instead of the stored procedure.
Here's a version where the array keys may not be the same for both arrays, but you want them all to be there in the final array.
function array_add_by_key( $array1, $array2 ) {
foreach ( $array2 as $k => $a ) {
if ( array_key_exists( $k, $array1 ) ) {
$array1[$k] += $a;
} else {
$array1[$k] = $a;
}
}
return $array1;
}
I just love getting information like BalusC gives here - and he is kind enough to help SO many people with such GOOD information that I regard his words as gospel, but I was not able to use that order of events to solve this same kind of timing issue in my project. Since BalusC put a great general reference here that I even bookmarked, I thought I would donate my solution for some advanced timing issues in the same place since it does solve the original poster's timing issues as well. I hope this code helps someone:
<p:pickList id="formPickList"
value="#{mediaDetail.availableMedia}"
converter="MediaPicklistConverter"
widgetVar="formsPicklistWidget"
var="mediaFiles"
itemLabel="#{mediaFiles.mediaTitle}"
itemValue="#{mediaFiles}" >
<f:facet name="sourceCaption">Available Media</f:facet>
<f:facet name="targetCaption">Chosen Media</f:facet>
</p:pickList>
<p:commandButton id="viewStream_btn"
value="Stream chosen media"
icon="fa fa-download"
ajax="true"
action="#{mediaDetail.prepareStreams}"
update=":streamDialogPanel"
oncomplete="PF('streamingDialog').show()"
styleClass="ui-priority-primary"
style="margin-top:5px" >
<p:ajax process="formPickList" />
</p:commandButton>
The dialog is at the top of the XHTML outside this form and it has a form of its own embedded in the dialog along with a datatable which holds additional commands for streaming the media that all needed to be primed and ready to go when the dialog is presented. You can use this same technique to do things like download customized documents that need to be prepared before they are streamed to the user's computer via fileDownload buttons in the dialog box as well.
As I said, this is a more complicated example, but it hits all the high points of your problem and mine. When the command button is clicked, the result is to first insure the backing bean is updated with the results of the pickList, then tell the backing bean to prepare streams for the user based on their selections in the pick list, then update the controls in the dynamic dialog with an update, then show the dialog box ready for the user to start streaming their content.
The trick to it was to use BalusC's order of events for the main commandButton and then to add the <p:ajax process="formPickList" />
bit to ensure it was executed first - because nothing happens correctly unless the pickList updated the backing bean first (something that was not happening for me before I added it). So, yea, that commandButton rocks because you can affect previous, pending and current components as well as the backing beans - but the timing to interrelate all of them is not easy to get a handle on sometimes.
Happy coding!
You are using improper syntax. If you read the docs mysqli_query() you will find that it needs two parameter.
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
mysql $link
generally means, the resource object of the established mysqli connection to query the database.
So there are two ways of solving this problem
mysqli_query();
$myConnection= mysqli_connect("$db_host","$db_username","$db_pass", "mrmagicadam") or die ("could not connect to mysql");
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysqli_query($myConnection, $sqlCommand) or die(mysqli_error($myConnection));
Or, Using mysql_query()
(This is now obselete)
$myConnection= mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysql_select_db("mrmagicadam") or die ("no database");
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysql_query($sqlCommand) or die(mysql_error());
As pointed out in the comments, be aware of using die to just get the error. It might inadvertently give the viewer some sensitive information .
To return a value from a VBScript function, assign the value to the name of the function, like this:
Function getNumber
getNumber = "423"
End Function
I've managed to bind a custom model to an element at runtime. The code is here: http://jsfiddle.net/ZiglioNZ/tzD4T/457/
The interesting bit is that I apply the data-bind attribute to an element I didn't define:
var handle = slider.slider().find(".ui-slider-handle").first();
$(handle).attr("data-bind", "tooltip: viewModel.value");
ko.applyBindings(viewModel.value, $(handle)[0]);
To make an exact spacing, I use Padding
. An example with two images:
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Expanded(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Image.asset('images/user1.png'),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Image.asset('images/user2.png'),
),
)
],
),
Maybe you are looking for this plyr::revalue function:
mutate(dat, x = revalue(x, c("A" = "B")))
You can see plyr::mapvalues too.
Does your stored procedure only retrieve the data or modify it too? If it's used only for retrieving, you can convert the stored procedure into a function and use the Common Table Expressions (CTEs) without having to declare it, as follows:
with temp as (
select * from dbo.fnFunctionName(10, 20)
)
select col1, col2 from temp
However, whatever needs to be retrieved from the CTE should be used in one statement only. You cannot do a with temp as ...
and try to use it after a couple of lines of SQL. You can have multiple CTEs in one statement for more complex queries.
For example,
with temp1020 as (
select id from dbo.fnFunctionName(10, 20)
),
temp2030 as (
select id from dbo.fnFunctionName(20, 30)
)
select * from temp1020
where id not in (select id from temp2030)
From your pom.xml, try to remove spring repository entries, per default will download from maven repository. I have tried with 1.5.6.RELEASE and worked very well.
I'm using version 4.4.2 and none of the other answers worked for me. But adding useMongoClient
to the options and putting it into a variable that you call close
on seemed to work.
var db = mongoose.connect('mongodb://localhost:27017/somedb', { useMongoClient: true })
//do stuff
db.close()
I had the same problem. Here's what I figured out:
=BDP(A1&"@BGN Corp", "Issuer_parent_eqy_ticker")
A1 being the ISINs. This will return the ticker number. Then just use the ticker number to get the price.
Another Alternative for the command line that is easier than fighting with quotation marks is to put the json into a file, and use the @ prefix of curl parameters, e.g. with the following in json.txt:
{ "syncheader" : {
"servertimesync" : "20131126121749",
"deviceid" : "testDevice"
}
}
then in my case I issue:
curl localhost:9000/sync -H "Content-type:application/json" -X POST -d @json.txt
Keeps the json more readable too.
Recent Java comes with Java Virtual Machine Process Status Tool "jps"
http://download.oracle.com/javase/1.5.0/docs/tooldocs/share/jps.html
For example,
[nsushkin@fulton support]$ jps -m
2120 Main --userdir /home/nsushkin/.netbeans/7.0 --branding nb
26546 charles.jar
17600 Jps -m
Here's the main class from my collision detection program.
You can see it run at: http://www.youtube.com/watch?v=JIXhCvXgjsQ
/**
*
* @author Tyler Griffin
*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.GraphicsDevice.*;
import java.util.ArrayList;
import java.awt.Graphics;
import java.awt.geom.Line2D;
public class collision extends JFrame implements KeyListener, MouseMotionListener, MouseListener
{
ArrayList everything=new ArrayList<tile>();
int time=0, x, y, width, height, up=0, down=0, left=0, right=0, mouse1=0, mouse2=0;
int mouseX, mouseY;
GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice screen = environment.getDefaultScreenDevice();
DisplayMode displayMode = screen.getDisplayMode();
//private BufferStrategy strategy;
JLayeredPane pane = new JLayeredPane();
tile Tile;
circle Circle;
rectangle Rectangle;
textPane text;
public collision()
{
setUndecorated(screen.isFullScreenSupported());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLayout(null);
setResizable(false);
screen.setFullScreenWindow(this);
width=displayMode.getWidth();
height=displayMode.getHeight();
Circle=new circle(-(int)Math.round((double)height/7*2),-(int)Math.round((double)height/7*2),(int)Math.round((double)height/7*.85),this);
Rectangle=new rectangle(-(int)Math.round((double)height/7*1.5),-(int)Math.round((double)height/7*1.5),(int)Math.round((double)height/7*1.5),(int)Math.round((double)height/7*1.5),this);
Tile=Circle;
Tile.move(mouseX-Tile.width/2, mouseY-Tile.height/2);
text=new textPane(0,0,width,height,this);
everything.add(new circle((int)Math.round((double)width/100*75),(int)Math.round((double)height/100*15),(int)Math.round((double)width/100*10),this));
everything.add(new rectangle((int)Math.round((double)width/100*70),(int)Math.round((double)height/100*60),(int)Math.round((double)width/100*20),(int)Math.round((double)height/100*20),this));
//everything.add(new line(750,250,750,750,this));
/*everything.add(new line(width/700*419,height/700*68,width/700*495,height/700*345,this));
everything.add(new line(width/700*495,height/700*345,width/700*749,height/700*350,this));
everything.add(new line(width/700*749,height/700*350,width/700*549,height/700*519,this));
everything.add(new line(width/700*549,height/700*519,width/700*624,height/700*800,this));
everything.add(new line(width/700*624,height/700*800,width/700*419,height/700*638,this));
everything.add(new line(width/700*419,height/700*638,width/700*203,height/700*800,this));
everything.add(new line(width/700*203,height/700*800,width/700*279,height/700*519,this));
everything.add(new line(width/700*279,height/700*519,width/700*76,height/700*350,this));
everything.add(new line(width/700*76,height/700*350,width/700*333,height/700*345,this));
everything.add(new line(width/700*333,height/700*345,width/700*419,height/700*68,this));
everything.add(new line(width/950*419,height/700*68,width/950*624,height/700*800,this));
everything.add(new line(width/950*419,height/700*68,width/950*203,height/700*800,this));
everything.add(new line(width/950*76,height/700*350,width/950*624,height/700*800,this));
everything.add(new line(width/950*203,height/700*800,width/950*749,height/700*350,this));
everything.add(new rectangle(width/950*76,height/700*350,width/950*673,1,this));*/
everything.add(new line((int)Math.round((double)width/1350*419),(int)Math.round((double)height/1000*68),(int)Math.round((double)width/1350*624),(int)Math.round((double)height/1000*800),this));
everything.add(new line((int)Math.round((double)width/1350*419),(int)Math.round((double)height/1000*68),(int)Math.round((double)width/1350*203),(int)Math.round((double)height/1000*800),this));
everything.add(new line((int)Math.round((double)width/1350*76),(int)Math.round((double)height/1000*350),(int)Math.round((double)width/1350*624),(int)Math.round((double)height/1000*800),this));
everything.add(new line((int)Math.round((double)width/1350*203),(int)Math.round((double)height/1000*800),(int)Math.round((double)width/1350*749),(int)Math.round((double)height/1000*350),this));
everything.add(new rectangle((int)Math.round((double)width/1350*76),(int)Math.round((double)height/1000*350),(int)Math.round((double)width/1350*673),1,this));
addKeyListener(this);
addMouseMotionListener(this);
addMouseListener(this);
}
public void keyReleased(KeyEvent e)
{
Object source=e.getSource();
int released=e.getKeyCode();
if (released==KeyEvent.VK_A){left=0;}
if (released==KeyEvent.VK_W){up=0;}
if (released==KeyEvent.VK_D){right=0;}
if (released==KeyEvent.VK_S){down=0;}
}//end keyReleased
public void keyPressed(KeyEvent e)
{
Object source=e.getSource();
int pressed=e.getKeyCode();
if (pressed==KeyEvent.VK_A){left=1;}
if (pressed==KeyEvent.VK_W){up=1;}
if (pressed==KeyEvent.VK_D){right=1;}
if (pressed==KeyEvent.VK_S){down=1;}
if (pressed==KeyEvent.VK_PAUSE&&pressed==KeyEvent.VK_P)
{
//if (paused==0){paused=1;}
//else paused=0;
}
}//end keyPressed
public void keyTyped(KeyEvent e){}
//***********************************************************************************************
public void mouseDragged(MouseEvent e)
{
mouseX=(e.getX());
mouseY=(e.getY());
//run();
}
public void mouseMoved(MouseEvent e)
{
mouseX=(e.getX());
mouseY=(e.getY());
//run();
}
//***********************************************************************************************
public void mousePressed(MouseEvent e)
{
if(e.getX()==0 && e.getY()==0){System.exit(0);}
mouseX=(e.getX()+x);
mouseY=(e.getY()+y);
if(Tile instanceof circle)
{
Circle.move(0-Circle.width, 0-Circle.height);
Circle.setBounds(Circle.x, Circle.y, Circle.width, Circle.height);
Tile=Rectangle;
}
else
{
Rectangle.move(0-Rectangle.width, 0-Rectangle.height);
Rectangle.setBounds(Rectangle.x, Rectangle.y, Rectangle.width, Rectangle.height);
Tile=Circle;
}
Tile.move(mouseX-Tile.width/2, mouseY-Tile.height/2);
}
public void mouseReleased(MouseEvent e)
{
//run();
}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseClicked(MouseEvent e){}
//***********************************************************************************************
public void run()//run collision detection
{
while (this == this)
{
Tile.move(Tile.x + ((mouseX - (Tile.x + (Tile.width / 2))) / 10), Tile.y + ((mouseY - (Tile.y + (Tile.height / 2))) / 10));
//Tile.move((mouseX - Tile.width / 2), mouseY - (Tile.height / 2));
for (int i = 0; i < everything.size(); i++)
{
tile Temp = (tile) everything.get(i);
if (Temp.x < (Tile.x + Tile.width) && (Temp.x + Temp.width) > Tile.x && Temp.y < (Tile.y + Tile.height) && (Temp.y + Temp.height) > Tile.y)//rectangles collided
{
if (Temp instanceof rectangle)
{
if (Tile instanceof rectangle){rectangleRectangle(Temp);}
else {circleRectangle(Temp);}//Tile instanceof circle
}
else
{
if (Temp instanceof circle)
{
if (Tile instanceof rectangle) {rectangleCircle(Temp);}
else {circleCircle(Temp);}
}
else//line
{
if (Tile instanceof rectangle){rectangleLine(Temp);}
else{circleLine(Temp);}
}
}
}//end if
}//end for
try {Thread.sleep(16L);}
catch (Exception e) {}
Tile.setBounds(Tile.x, Tile.y, Tile.width, Tile.height);
//Rectangle.setBounds(x, y, width, height);
//Circle.setBounds(x, y, width, height);
repaint();
text.out=" ";
}//end while loop
}//end run
//***************************************special collision detection/handling functions************************************************
void rectangleRectangle(tile Temp)
{
int lapTop, lapBot, lapLeft, lapRight, small, scootX=0, scootY=0;
lapTop=(Temp.y+Temp.height)-Tile.y;
lapBot=(Tile.y+Tile.height)-Temp.y;
lapLeft=(Temp.x+Temp.width)-Tile.x;
lapRight=(Tile.x+Tile.width)-Temp.x;
small=999999999;
if (lapTop<small){small=lapTop; scootX=0; scootY=lapTop;}
if (lapBot<small){small=lapBot; scootX=0; scootY=lapBot*-1;}
if (lapLeft<small){small=lapLeft; scootX=lapLeft; scootY=0;}
if (lapRight<small){small=lapRight; scootX=lapRight*-1; scootY=0;}
Tile.move(Tile.x+scootX, Tile.y+scootY);text.out="collision detected!";
}
void circleRectangle(tile Temp)
{
if((Tile.x+Tile.width/2<=Temp.x+Temp.width && Tile.x+Tile.width/2>=Temp.x)||(Tile.y+Tile.height/2>=Temp.y && Tile.y+Tile.height/2<=Temp.y+Temp.height))
{
rectangleRectangle(Temp);
}
else//push from nearest corner
{
int x,y;
if(Tile.x+Tile.width/2>Temp.x+Temp.width && Tile.y+Tile.height/2<Temp.y){x=Temp.x+Temp.width; y=Temp.y;}
else if(Tile.x+Tile.width/2<Temp.x && Tile.y+Tile.height/2<Temp.y){x=Temp.x; y=Temp.y;}
else if(Tile.x+Tile.width/2>Temp.x+Temp.width && Tile.y+Tile.height/2>Temp.y+Temp.height){x=Temp.x+Temp.width; y=Temp.y+Temp.height;}
else {x=Temp.x; y=Temp.y+Temp.height;}
double distance = Math.sqrt(Math.pow(Tile.x+(Tile.width/2) - x, 2) + Math.pow(Tile.y+(Tile.height/2) - y, 2));
if((int)Math.round(distance)<Tile.height/2)
{
double normY = ((Tile.y+(Tile.height/2) - y) / distance);
double normX = ((Tile.x+(Tile.width/2) - x) / distance);
Tile.move(x-Tile.width/2+(int)Math.round(normX*((Tile.width/2))) , y-Tile.height/2+(int)Math.round(normY*((Tile.height/2))));text.out="collision detected!";
}
}
}
void rectangleCircle(tile Temp)
{
if((Temp.x+Temp.width/2<=Tile.x+Tile.width && Temp.x+Temp.width/2>=Tile.x)||(Temp.y+Temp.height/2>=Tile.y && Temp.y+Temp.height/2<=Tile.y+Tile.height))
{
rectangleRectangle(Temp);
}
else//push from nearest corner
{
int x,y;
if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2<Tile.y){x=Tile.x+Tile.width; y=Tile.y;}
else if(Temp.x+Temp.width/2<Tile.x && Temp.y+Temp.height/2<Tile.y){x=Tile.x; y=Tile.y;}
else if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2>Tile.y+Tile.height){x=Tile.x+Tile.width; y=Tile.y+Tile.height;}
else {x=Tile.x; y=Tile.y+Tile.height;}
double distance = Math.sqrt(Math.pow(Temp.x+(Temp.width/2) - x, 2) + Math.pow(Temp.y+(Temp.height/2) - y, 2));
if((int)Math.round(distance)<Temp.height/2)
{
double normY = ((Temp.y+(Temp.height/2) - y) / distance);
double normX = ((Temp.x+(Temp.width/2) - x) / distance);
if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2<Tile.y){Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2)))-Tile.width,(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2))));text.out="collision detected!";}
else if(Temp.x+Temp.width/2<Tile.x && Temp.y+Temp.height/2<Tile.y){Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2))),(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2))));text.out="collision detected!";}
else if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2>Tile.y+Tile.height){Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2)))-Tile.width,(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2)))-Tile.height);text.out="collision detected!";}
else {Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2))),(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2)))-Tile.height);text.out="collision detected!";}
}
}
}
void circleCircle(tile Temp)
{
double distance = Math.sqrt(Math.pow((Tile.x+(Tile.width/2)) - (Temp.x+(Temp.width/2)),2) + Math.pow((Tile.y+(Tile.height/2)) - (Temp.y+(Temp.height/2)), 2));
if((int)distance<(Tile.width/2+Temp.width/2))
{
double normX = ((Tile.x+(Tile.width/2)) - (Temp.x+(Temp.width/2))) / distance;
double normY = ((Tile.y+(Tile.height/2)) - (Temp.y+(Temp.height/2))) / distance;
Tile.move((Temp.x+(Temp.width/2))+(int)Math.round(normX*(Tile.width/2+Temp.width/2))-(Tile.width/2) , (Temp.y+(Temp.height/2))+(int)Math.round(normY*(Tile.height/2+Temp.height/2))-(Tile.height/2));text.out="collision detected!";
}
}
void circleLine(tile Temp)
{
line Line=(line)Temp;
if (Line.x1 < (Tile.x + Tile.width) && (Line.x1) > Tile.x && Line.y1 < (Tile.y + Tile.height) && Line.y1 > Tile.y)//circle may be hitting one of the end points
{
rectangle rec=new rectangle(Line.x1, Line.y1, 1, 1, this);
circleRectangle(rec);
remove(rec);
}
if (Line.x2 < (Tile.x + Tile.width) && (Line.x2) > Tile.x && Line.y2 < (Tile.y + Tile.height) && Line.y2 > Tile.y)//circle may be hitting one of the end points
{
rectangle rec=new rectangle(Line.x2, Line.y2, 1, 1, this);
circleRectangle(rec);
remove(rec);
}
int x1=0, y1=0, x2=Tile.x+(Tile.width/2), y2=Tile.y+(Tile.height/2);
x1=Tile.x+(Tile.width/2)-Line.height;//(int)Math.round(Line.xNorm*1000);
x2=Tile.x+(Tile.width/2)+Line.height;
if(Line.posSlope)
{
y1=Tile.y+(Tile.height/2)-Line.width;
y2=Tile.y+(Tile.height/2)+Line.width;
}
else
{
y1=Tile.y+(Tile.height/2)+Line.width;
y2=Tile.y+(Tile.height/2)-Line.width;
}
Point point=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection
if (point.x < (Line.x + Line.width) && point.x > Line.x && point.y < (Line.y + Line.height) && point.y > Line.y)//line intersects within line segment
{
//if(point!=null){System.out.println(point.x+","+point.y);}
double distance = Math.sqrt(Math.pow((Tile.x+(Tile.width/2)) - point.x,2) + Math.pow((Tile.y+(Tile.width/2)) - point.y, 2));
if((int)distance<Tile.width/2)
{
//System.out.println("hit");
double normX = ((Tile.x+(Tile.width/2)) - point.x) / distance;
double normY = ((Tile.y+(Tile.height/2)) - point.y) / distance;
Tile.move((point.x)+(int)Math.round(normX*(Tile.width/2))-(Tile.width/2) , (point.y)+(int)Math.round(normY*(Tile.height/2))-(Tile.height/2));text.out="collision detected!";
//System.out.println(point.x+","+point.y);
}
}
//new bullet(this, (int)Math.round(tryX), (int)Math.round(tryY));
}
void rectangleLine(tile Temp)
{
line Line=(line)Temp;
if(new Line2D.Double(Line.x1,Line.y1,Line.x2,Line.y2).intersects(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height)))
{
if (Line.x1 < (Tile.x + Tile.width) && (Line.x1) > Tile.x && Line.y1 < (Tile.y + Tile.height) && Line.y1 > Tile.y)//circle may be hitting one of the end points
{
rectangle rec=new rectangle(Line.x1, Line.y1, 1, 1, this);
rectangleRectangle(rec);
remove(rec);
}
if (Line.x2 < (Tile.x + Tile.width) && (Line.x2) > Tile.x && Line.y2 < (Tile.y + Tile.height) && Line.y2 > Tile.y)//circle may be hitting one of the end points
{
rectangle rec=new rectangle(Line.x2, Line.y2, 1, 1, this);
rectangleRectangle(rec);
remove(rec);
}
if(Line.posSlope)//positive sloped line
{
//first we'll do the top left corner
int x1=Tile.x-Line.height;
int x2=Tile.x+Line.height;
int y1=Tile.y-Line.width;
int y2=Tile.y+Line.width;
Point topPoint=new Point(-99,-99), botPoint=new Point(-99,-99);
double topDistance=0, botDistance=0;
topPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection
topDistance = Math.sqrt(Math.pow(Tile.x - topPoint.x,2) + Math.pow(Tile.y - topPoint.y, 2));
//new let's do the bottom right corner
x1=Tile.x+Tile.width-Line.height;
x2=Tile.x+Tile.width+Line.height;
y1=Tile.y+Tile.height-Line.width;
y2=Tile.y+Tile.height+Line.width;
botPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection
botDistance = Math.sqrt(Math.pow((Tile.x+Tile.width) - botPoint.x,2) + Math.pow((Tile.y+Tile.height) - botPoint.y, 2));
if(topDistance<botDistance)
{
if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(topPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(topPoint))
{
Tile.move(topPoint.x,topPoint.y);text.out="collision detected!";
}
}
else
{
if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(botPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(botPoint))
{
Tile.move(botPoint.x-Tile.width,botPoint.y-Tile.height);text.out="collision detected!";
}
}
}
else//negative sloped lne
{
//first we'll do the top right corner
int x1=Tile.x+Tile.width-Line.height;
int x2=Tile.x+Tile.width+Line.height;
int y1=Tile.y+Line.width;
int y2=Tile.y-Line.width;
Point topPoint=new Point(-99,-99), botPoint=new Point(-99,-99);
double topDistance=0, botDistance=0;
topPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection
topDistance = Math.sqrt(Math.pow(Tile.x + Tile.width - topPoint.x,2) + Math.pow(Tile.y - topPoint.y, 2));
//new let's do the bottom left corner
x1=Tile.x-Line.height;
x2=Tile.x+Line.height;
y1=Tile.y+Tile.height+Line.width;
y2=Tile.y+Tile.height-Line.width;
botPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection
botDistance = Math.sqrt(Math.pow(Tile.x - botPoint.x,2) + Math.pow((Tile.y+Tile.height) - botPoint.y, 2));
if(topDistance<botDistance)
{
if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(topPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(topPoint))
{
Tile.move(topPoint.x-Tile.width,topPoint.y);text.out="collision detected!";
}
}
else
{
if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(botPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(botPoint))
{
Tile.move(botPoint.x,botPoint.y-Tile.height);text.out="collision detected!";
}
}
}
}
}
public Point intersection(double x1, double y1, double x2, double y2,double x3, double y3, double x4, double y4)//I didn't write this. got it from http://www.ahristov.com/tutorial/geometry-games/intersection-lines.html (I altered it)
{
double d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
double xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d;
double yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d;
int x=(int)Math.round(xi);
int y=(int)Math.round(yi);
return new Point(x, y);
}
//***************************************************************************************
public static void main(String[] args)
{
final collision Collision=new collision();
Collision.run();
}//end main
}//end class
You might look at how pygame handles this to steal some ideas.
From RFC 4918 (and also documented at http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml):
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
try this one, it is working fine for me.
"^([a-zA-Z])[a-zA-Z0-9-_]*$"
Tested in Ubuntu 16.04
# Create the docker group and add your user to the docker group
groupadd docker
usermod -aG docker $USER
newgrp docker
# Configure docker service to be exposed
mkdir -p /etc/systemd/system/docker.service.d
echo -e '[Service]\nExecStart=\nExecStart=/usr/bin/dockerd -H fd:// -H tcp://0.0.0.0:2376' >> /etc/systemd/system/docker.service.d/override.conf
# restart service
systemctl daemon-reload
service docker restart
Working on a project that has a lot of modals calling other modals and a few HTML guys that might not know to initiate it everytime for each button. Came to a similar conclusion as @gmaggio, begrudgingly after going the long way around first.
EDIT: Now supports modals called via javascript.
EDIT: Opening a scrolling modal from another modal now works.
$(document).on('show.bs.modal', function (event) {
if (!event.relatedTarget) {
$('.modal').not(event.target).modal('hide');
};
if ($(event.relatedTarget).parents('.modal').length > 0) {
$(event.relatedTarget).parents('.modal').modal('hide');
};
});
$(document).on('shown.bs.modal', function (event) {
if ($('body').hasClass('modal-open') == false) {
$('body').addClass('modal-open');
};
});
Just place the modal calling button in as normal, and if it is picked up to be inside a modal, it will close the current one first before opening the one specified in data-target.
Note that relatedTarget
is provided by Bootstrap.
I also added the following to smooth out the fading a bit: I am sure more can be done though.
.modal-backdrop.fade + .modal-backdrop.fade {
transition: opacity 0.40s linear 0s;
}
Faced more issues while making this work. Here are the details:
apache-log4j-extras-1.1.jar
in the classpath, didn't notice this at first.RollingFileAppender
should be org.apache.log4j.rolling.RollingFileAppender
instead of org.apache.log4j.RollingFileAppender
. This can give the error: log4j:ERROR No output stream or file set for the appender named [file].
log4j-1.2.14.jar
to log4j-1.2.16.jar
.Below is the appender configuration which worked for me:
<appender name="file" class="org.apache.log4j.rolling.RollingFileAppender">
<param name="threshold" value="debug" />
<rollingPolicy name="file"
class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
<param name="FileNamePattern" value="logs/MyLog-%d{yyyy-MM-dd-HH-mm}.log.gz" />
<!-- The below param will keep the live update file in a different location-->
<!-- param name="ActiveFileName" value="current/MyLog.log" /-->
</rollingPolicy>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%5p %d{ISO8601} [%t][%x] %c - %m%n" />
</layout>
</appender>
I had the same problem. I made a simple UIView category that fixes that.
.h
#import <UIKit/UIKit.h>
@interface UIView (GCLibrary)
@property (nonatomic, assign) CGFloat height;
@property (nonatomic, assign) CGFloat width;
@property (nonatomic, assign) CGFloat x;
@property (nonatomic, assign) CGFloat y;
@end
.m
#import "UIView+GCLibrary.h"
@implementation UIView (GCLibrary)
- (CGFloat) height {
return self.frame.size.height;
}
- (CGFloat) width {
return self.frame.size.width;
}
- (CGFloat) x {
return self.frame.origin.x;
}
- (CGFloat) y {
return self.frame.origin.y;
}
- (CGFloat) centerY {
return self.center.y;
}
- (CGFloat) centerX {
return self.center.x;
}
- (void) setHeight:(CGFloat) newHeight {
CGRect frame = self.frame;
frame.size.height = newHeight;
self.frame = frame;
}
- (void) setWidth:(CGFloat) newWidth {
CGRect frame = self.frame;
frame.size.width = newWidth;
self.frame = frame;
}
- (void) setX:(CGFloat) newX {
CGRect frame = self.frame;
frame.origin.x = newX;
self.frame = frame;
}
- (void) setY:(CGFloat) newY {
CGRect frame = self.frame;
frame.origin.y = newY;
self.frame = frame;
}
@end
Here's a demo of the above:https://jsfiddle.net/sajadweb/mjnyLm0q/11
new Vue({_x000D_
el: '#app',_x000D_
data: {_x000D_
users: [{ name: 'sajadweb',email:'[email protected]' }] _x000D_
},_x000D_
methods: {_x000D_
addUser: function () {_x000D_
this.users.push({ name: '',email:'' });_x000D_
},_x000D_
deleteUser: function (index) {_x000D_
console.log(index);_x000D_
console.log(this.finds);_x000D_
this.users.splice(index, 1);_x000D_
if(index===0)_x000D_
this.addUser()_x000D_
}_x000D_
}_x000D_
});
_x000D_
<script src="https://unpkg.com/vue/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
<h1>Add user</h1>_x000D_
<div v-for="(user, index) in users">_x000D_
<input v-model="user.name">_x000D_
<input v-model="user.email">_x000D_
<button @click="deleteUser(index)">_x000D_
delete_x000D_
</button>_x000D_
</div>_x000D_
_x000D_
<button @click="addUser">_x000D_
New User_x000D_
</button>_x000D_
_x000D_
<pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
Try the instanceof
operator: it seems that all functions inherit from the Function
class:
// Test data
var f1 = function () { alert("test"); }
var o1 = { Name: "Object_1" };
F_est = function () { };
var o2 = new F_est();
// Results
alert(f1 instanceof Function); // true
alert(o1 instanceof Function); // false
alert(o2 instanceof Function); // false
find . -name "*.ear" -exec ls -l {} \;
SELECT column_Name1,column_name2,......
From tbl_name1,tbl_name2,tbl_name3
where tbl_name1.column_name = tbl_name2.column_name
and tbl_name2.column_name = tbl_name3.column_name
Dockers use images which are build in layers. This adds a lot in terms of portability, sharing, versioning and other features. These images are very easy to port or transfer and since they are in layers, changes in subsequent versions are added in form of layers over previous layers. So, while porting many a times you don't need to port the base layers. Dockers have containers which run these images with execution environment contained, they add changes as new layers providing easy version control.
Apart from that Docker Hub is a good registry with thousands of public images, where you can find images which have OS and other softwares installed. So, you can get a pretty good head start for your application.
if (Request.Params["__EVENTTARGET"] != null)
{
if (Request.Params["__EVENTTARGET"].ToString().Contains("myControlID"))
{
DoWhateverYouWant();
}
}
The link above is rather outdated. For WebLogic 12c you may define the transaction timout in a transaction-descriptor for each EJB in the WebLogic deployment descriptor weblogic-ejb-jar.xml, see weblogic-ejb-jar.xml Deployment Descriptor Reference.
For a message driven been it looks like this:
<weblogic-enterprise-bean>
<ejb-name>TestMessageBeanLow</ejb-name>
<message-driven-descriptor>
<pool>
<max-beans-in-free-pool>1</max-beans-in-free-pool>
</pool>
<destination-jndi-name>jms/ActiveMQ/TestRequestQueue_LOW</destination-jndi-name>
<connection-factory-jndi-name>jms/ActiveMQ/TestConnectionFactory</connection-factory-jndi-name>
</message-driven-descriptor>
<transaction-descriptor>
<trans-timeout-seconds>60</trans-timeout-seconds>
</transaction-descriptor>
<resource-description>
<res-ref-name>jms/ConnectionFactory</res-ref-name>
<jndi-name>jms/ActiveMQ/TestConnectionFactory</jndi-name>
</resource-description>
</weblogic-enterprise-bean>
Note that if the user may be in multiple zones used in the query, you may probably want to add .distinct()
. Otherwise you get one user multiple times:
users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3]).distinct()
If you've have added the django-storages
module (to support uploading files to S3 in your django app for instance), and if like me you did not read correctly the documentation of this module, just remove this line from your settings.py
:
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
Otherwise it will cause your static assets to be looked NOT on your local machine but remotely in the S3 bucket, including admin panel CSS, and thus effectively breaking admin panel CSS.
In AngularJS2 I found a new way, maybe is just the same thing but in this new version :
import {Router, RouteConfig, ROUTER_DIRECTIVES, Location} from 'angular2/router';
(...)
constructor(private _router: Router, private _location: Location) {}
onSubmit() {
(...)
self._location.back();
}
After my function, I can see that my application is going to the previous page usgin location from angular2/router.
https://angular.io/docs/ts/latest/api/common/index/Location-class.html
I don't think so. The API's will provide access to delayed quotes, there is no way that real time data or tick data, will be provided for free.
MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text);
mm.Subject = txtSubject.Text;
mm.Body = txtBody.Text;
if (fuAttachment.HasFile)//file upload select or not
{
string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
}
mm.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
Response.write("Send Mail");
View Video: https://www.youtube.com/watch?v=bUUNv-19QAI
Usually, IPython's %time
, %timeit
, %prun
and %lprun
(if one has line_profiler
installed) satisfy my profiling needs quite well. However, a use case for tic-toc
-like functionality arose when I tried to profile calculations that were interactively driven, i.e., by the user's mouse motion in a GUI. I felt like spamming tic
s and toc
s in the sources while testing interactively would be the fastest way to reveal the bottlenecks. I went with Eli Bendersky's Timer
class, but wasn't fully happy, since it required me to change the indentation of my code, which can be inconvenient in some editors and confuses the version control system. Moreover, there may be the need to measure the time between points in different functions, which wouldn't work with the with
statement. After trying lots of Python cleverness, here is the simple solution that I found worked best:
from time import time
_tstart_stack = []
def tic():
_tstart_stack.append(time())
def toc(fmt="Elapsed: %s s"):
print fmt % (time() - _tstart_stack.pop())
Since this works by pushing the starting times on a stack, it will work correctly for multiple levels of tic
s and toc
s. It also allows one to change the format string of the toc
statement to display additional information, which I liked about Eli's Timer
class.
For some reason I got concerned with the overhead of a pure Python implementation, so I tested a C extension module as well:
#include <Python.h>
#include <mach/mach_time.h>
#define MAXDEPTH 100
uint64_t start[MAXDEPTH];
int lvl=0;
static PyObject* tic(PyObject *self, PyObject *args) {
start[lvl++] = mach_absolute_time();
Py_RETURN_NONE;
}
static PyObject* toc(PyObject *self, PyObject *args) {
return PyFloat_FromDouble(
(double)(mach_absolute_time() - start[--lvl]) / 1000000000L);
}
static PyObject* res(PyObject *self, PyObject *args) {
return tic(NULL, NULL), toc(NULL, NULL);
}
static PyMethodDef methods[] = {
{"tic", tic, METH_NOARGS, "Start timer"},
{"toc", toc, METH_NOARGS, "Stop timer"},
{"res", res, METH_NOARGS, "Test timer resolution"},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC
inittictoc(void) {
Py_InitModule("tictoc", methods);
}
This is for MacOSX, and I have omitted code to check if lvl
is out of bounds for brevity. While tictoc.res()
yields a resolution of about 50 nanoseconds on my system, I found that the jitter of measuring any Python statement is easily in the microsecond range (and much more when used from IPython). At this point, the overhead of the Python implementation becomes negligible, so that it can be used with the same confidence as the C implementation.
I found that the usefulness of the tic-toc
-approach is practically limited to code blocks that take more than 10 microseconds to execute. Below that, averaging strategies like in timeit
are required to get a faithful measurement.
Me faced same problem, I got a solution using below technic. Copy the btn_check.xml
from android-sdk/platforms/android-#(version)/data/res/drawable
to your project's drawable folder and change the 'on' and 'off' image states to your custom images.
Then your xml will just need android:button="@drawable/btn_check"
<CheckBox
android:button="@drawable/btn_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true" />
If you want to use different default Android icons, you can use:
android:button="@android:drawable/..."
The specific problem is that you're declaring a new variable instead of assigning to an existing one:
char * ret = new char[strlen(array) + 1 + 1];
^^^^^^ Remove this
and trying to compare string values by comparing pointers:
if (array!="") // Wrong - compares pointer with address of string literal
if (array[0] == 0) // Better - checks for empty string
although there's no need to make that comparison at all; the first branch will do the right thing whether or not the string is empty.
The more general problem is that you're messing around with nasty, error-prone C-style string manipulation in C++. Use std::string
and it will manage all the memory allocation for you:
std::string appendCharToString(std::string const & s, char a) {
return s + a;
}
Credentials do not work if API is not enabled. In my case the next steps were needed:
You can do something like this instead.
return new DateTime(2010, Month, 1).ToString("MMM");
You can use a formula like:
(weekday + 5) % 7 + 1
If you decide to use this, it would be worth running through some examples to convince yourself that it actually does what you want.
addition: for not to be affected by the DATEFIRST variable (it could be set to any value between 1 and 7) the real formula is :
(weekday + @@DATEFIRST + 5) % 7 + 1
Add z-index:-1
and position:relative
to .content
#header {_x000D_
background: url(http://placehold.it/420x160) center top no-repeat;_x000D_
}_x000D_
#header-inner {_x000D_
background: url(http://placekitten.com/150/200) right top no-repeat;_x000D_
}_x000D_
.logo-class {_x000D_
height: 128px;_x000D_
}_x000D_
.content {_x000D_
margin-left: auto;_x000D_
margin-right: auto;_x000D_
table-layout: fixed;_x000D_
border-collapse: collapse;_x000D_
z-index: -1;_x000D_
position:relative;_x000D_
}_x000D_
.td-main {_x000D_
text-align: center;_x000D_
padding: 80px 10px 80px 10px;_x000D_
border: 1px solid #A02422;_x000D_
background: #ABABAB;_x000D_
}
_x000D_
<body>_x000D_
<div id="header">_x000D_
<div id="header-inner">_x000D_
<table class="content">_x000D_
<col width="400px" />_x000D_
<tr>_x000D_
<td>_x000D_
<table class="content">_x000D_
<col width="400px" />_x000D_
<tr>_x000D_
<td>_x000D_
<div class="logo-class"></div>_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td id="menu"></td>_x000D_
</tr>_x000D_
</table>_x000D_
<table class="content">_x000D_
<col width="120px" />_x000D_
<col width="160px" />_x000D_
<col width="120px" />_x000D_
<tr>_x000D_
<td class="td-main">text</td>_x000D_
<td class="td-main">text</td>_x000D_
<td class="td-main">text</td>_x000D_
</tr>_x000D_
</table>_x000D_
</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
<!-- header-inner -->_x000D_
</div>_x000D_
<!-- header -->_x000D_
</body>
_x000D_
As mentioned above, by default text editors will not use UTF-8 as the standard encoding for documents. However most editors will allow you to change that in the settings. Even for each specific document.
From gsitgithub/find-currupt-jars.txt, the following command lists all the corrupted jar files in the repository:
find /home/me/.m2/repository/ -name "*jar" | xargs -L 1 zip -T | grep error | grep invalid
You can delete the corrupted jar files, and recompile the project.
Example output:
warning [/cygdrive/J/repo/net/java/dev/jna/jna/4.1.0/jna-4.1.0.jar]: 98304 extra bytes at beginning or within zipfile
(attempting to process anyway)
file #1: bad zipfile offset (local header sig): 98304
(attempting to re-compensate)
zip error: Zip file invalid, could not spawn unzip, or wrong unzip (original files unmodified)
Try: if(parseInt(order)>0){....
What I would do is use this tool and step through where you are getting the exception
Read this it will tell you how to create PDB's so you do not have to have all your references setup.
http://www.cplotts.com/2011/01/14/net-reflector-pro-debugging-the-net-framework-source-code/
It is a trial and I am not related to redgate at all I just use there software.
You can use below code to print time in HH:mm format, In my case Property type is TimeSpan So the value is coming in HH:mm:tt format but I have to show in above format ie. HH:mm
So you can use this code:
@Html.TextBoxFor(x =>x.mTimeFrom, null, new {@Value =Model.mTimeFrom.ToString().Substring(0,5), @class = "form-control success" })
cat *.png | ffmpeg -f image2pipe -i - output.mp4
from wiki
try {
} catch (javax.script.ScriptException ex) {
// System.out.println(ex.getMessage());
}
=COUNTIFS(H5:H21000,">=100", H5:H21000,"<999")
<script type="text/javascript">
function Check() {
if (document.getElementById('yesCheck').checked) {
document.getElementById('ifYes').style.display = 'block';
}
else {
document.getElementById('ifYes').style.display = 'none';
}
}
</script>
</head>
<body>
Select os :
<br>
Two
<input type="radio" onclick="Check();" value="Two" name="categor`enter code here`y" id="yesCheck"/>One
<input type="radio" onclick="Check();" value="One"name="category"/>
<br>
<div id="ifYes" style="display:none" >
Three<input type="radio" name="win" value="Three"/>
Four<input type="radio" name="win" value="Four"/>
The original version can be diferent, but is necessary change it at 0.10.0 or 0.13.9 version that fix the problem
You can run the actual Ken Reitz's httpbin
server locally (under docker or on bare metal):
https://github.com/postmanlabs/httpbin
docker pull kennethreitz/httpbin
docker run -p 80:80 kennethreitz/httpbin
## install dependencies
pip3 install gunicorn decorator httpbin werkzeug Flask flasgger brotlipy gevent meinheld six pyyaml
## start the server
gunicorn -b 0.0.0.0:8000 httpbin:app -k gevent
Now you have your personal httpbin instance running on http://0.0.0.0:8000 (visible to all of your LAN)
sudo chown -R yourname:www-data cake
then
sudo chmod -R g+s cake
First command changes owner and group.
Second command adds s attribute which will keep new files and directories within cake having the same group permissions.
Since you don't call Num.__init__
, the field "n1" never gets created. Call it and then it will be there.
Make sure it's not redefined again lower down in your settings.py. The default settings has:
ALLOWED_HOSTS = []
I haven't seen any decompilers that generate C++ code. I've seen a few experimental ones that make a reasonable attempt at generating C code, but they tended to be dependent on matching the code-generation patterns of a particular compiler (that may have changed, it's been awhile since I last looked into this). Of course any symbolic information will be gone. Google for "decompiler".
This can be done in one line.
{{corretor.isAdministrador && 'YES' || 'NÂO'}}
Usage in a td
tag:
<td class="text-center">{{corretor.isAdministrador && 'Sim' || 'Não'}}</td>
After struggling a bit with some of the answers here, I found a library called backoff that worked better for my situation. A basic example:
import backoff
@backoff.on_exception(
backoff.expo,
requests.exceptions.RequestException,
max_tries=5,
giveup=lambda e: e.response is not None and e.response.status_code < 500
)
def publish(self, data):
r = requests.post(url, timeout=10, json=data)
r.raise_for_status()
I'd still recommend giving the library's native functionality a shot, but if you run into any problems or need broader control, backoff is an option.
It's important to point out that install
and install:install
are different things, install
is a phase, in which maven do more than just install current project modules artifacs to local repository, it check remote repository first. On the other hand, install:install
is a goal, it just build your current project and install all it's artifacts to local repository (e.g. into the .m2
directory).
First, convert the timestamp using the built-in eloquent functionality, as described in this answer.
Then you can just use Carbon's min()
or max()
function for comparison. For example:
$dt1 = Carbon::create(2012, 1, 1, 0, 0, 0);
$dt2 = Carbon::create(2014, 1, 30, 0, 0, 0);
echo $dt1->min($dt2);
This will echo
the lesser of the two dates, which in this case is $dt1
.
An efficient command line tool, open source, free of any fee, available on both linux & windows : simply named pdftotext. This tool is a part of the xpdf library.
I guess you're coming from a windows background. So i'll contrast them (i'm kind of new to linux too). I found user's reply to my comment, to be useful in figuring things out.
In Windows, a variable can be permanent or not. The term Environment variable includes a variable set in the cmd shell with the SET command, as well as when the variable is set within the windows GUI, thus set in the registry, and becoming viewable in new cmd windows. e.g. documentation for the set command in windows https://technet.microsoft.com/en-us/library/bb490998.aspx "Displays, sets, or removes environment variables. Used without parameters, set displays the current environment settings." In Linux, set does not display environment variables, it displays shell variables which it doesn't call/refer to as environment variables. Also, Linux doesn't use set to set variables(apart from positional parameters and shell options, which I explain as a note at the end), only to display them and even then only to display shell variables. Windows uses set for setting and displaying e.g. set a=5, linux doesn't.
In Linux, I guess you could make a script that sets variables on bootup, e.g. /etc/profile
or /etc/.bashrc
but otherwise, they're not permanent. They're stored in RAM.
There is a distinction in Linux between shell variables, and environment variables. In Linux, shell variables are only in the current shell, and Environment variables, are in that shell and all child shells.
You can view shell variables with the set
command (though note that unlike windows, variables are not set in linux with the set command).
set -o posix; set
(doing that set -o posix once first, helps not display too much unnecessary stuff). So set
displays shell variables.
You can view environment variables with the env
command
shell variables are set with e.g. just a = 5
environment variables are set with export, export also sets the shell variable
Here you see shell variable zzz set with zzz = 5, and see it shows when running set
but doesn't show as an environment variable.
Here we see yyy set with export, so it's an environment variable. And see it shows under both shell variables and environment variables
$ zzz=5
$ set | grep zzz
zzz=5
$ env | grep zzz
$ export yyy=5
$ set | grep yyy
yyy=5
$ env | grep yyy
yyy=5
$
other useful threads
https://unix.stackexchange.com/questions/176001/how-can-i-list-all-shell-variables
https://askubuntu.com/questions/26318/environment-variable-vs-shell-variable-whats-the-difference
Note- one point which elaborates a bit and is somewhat corrective to what i've written, is that, in linux bash, 'set' can be used to set "positional parameters" and "shell options/attributes", and technically both of those are variables, though the man pages might not describe them as such. But still, as mentioned, set won't set shell variables or environment variables). If you do set asdf
then it sets $1 to asdf, and if you do echo $1
you see asdf. If you do set a=5
it won't set the variable a, equal to 5. It will set the positional parameter $1 equal to the string of "a=5". So if you ever saw set a=5 in linux it's probably a mistake unless somebody actually wanted that string a=5, in $1. The other thing that linux's set can set, is shell options/attributes. If you do set -o you see a list of them. And you can do for example set -o verbose
, off, to turn verbose on(btw the default happens to be off but that makes no difference to this). Or you can do set +o verbose
to turn verbose off. Windows has no such usage for its set command.
When adding new element with jquery plugin calls, you can do like the following:
$('<div>...</div>').hoverCard(function(){...}).appendTo(...)
var month = new Date().getMonth();
var newmon = month + 1;
$('#month').html((newmon < 10 ? '0' : '') + newmon );
I simply fixed your month issue, getMonth array start from 0 to 11.
>>> " xyz ".rstrip()
' xyz'
There is more about rstrip
in the documentation.
In Python 3, /
is float division
In Python 2, /
is integer division (assuming int
inputs)
In both 2 and 3, //
is integer division
(To get float division in Python 2 requires either of the operands be a float, either as 20.
or float(20)
)
The way to fix this sort of problem is to redefine the relevant list environment. The enumitem
package is my favourite way to do this sort of thing; it has many options and parameters that can be varied, either for all lists or for each list individually.
Here's how to do (something like) what it is I think you want:
\usepackage{enumitem} \setlist{nolistsep}
or
\usepackage{enumitem} \setlist{nosep}
The type of the SelectedValuePath
and the SelectedValue
must be EXACTLY the same.
If for example the type of SelectedValuePath
is Int16
and the type of the property that binds to SelectedValue
is int
it will not work.
I spend hours to find that, and that's why I am answering here after so much time the question was asked. Maybe another poor guy like me with the same problem can see it.
"1".PadLeft(4, '0');
You can pivot your DataFrame after creating:
>>> df = pd.DataFrame(data)
>>> df.pivot(index=0, columns=1, values=2)
# avg DataFrame
1 c1 c2
0
r1 avg11 avg12
r2 avg21 avg22
>>> df.pivot(index=0, columns=1, values=3)
# stdev DataFrame
1 c1 c2
0
r1 stdev11 stdev12
r2 stdev21 stdev22
You can make use of Google Guava utilities, as shown below
list = ImmutableSet.copyOf(list).asList();
This is probably the most efficient way of eliminating the duplicates from the list and interestingly, it preserves the iteration order as well.
UPDATE
But, in case, you don't want to involve Guava then duplicates can be removed as shown below.
ArrayList<String> list = new ArrayList<String>();
list.add("Krishna");
list.add("Krishna");
list.add("Kishan");
list.add("Krishn");
list.add("Aryan");
list.add("Harm");
System.out.println("List"+list);
HashSet hs = new HashSet();
hs.addAll(list);
list.clear();
list.addAll(hs);
But, of course, this will destroys the iteration order of the elements in the ArrayList.
Shishir
Using the same as approach as Romeo, I adapted it to Visual Studio 2010 :
<None Condition=" '$(Configuration)' == 'Debug' " Include="appDebug\App.config" />
<None Condition=" '$(Configuration)' == 'Release' " Include="appRelease\App.config" />
Here you need to keep both App.config files in different directories (appDebug and appRelease). I tested it and it works fine!
Since most of the ansswers seem to be outdated here is the setting that worked for me:
elasticsearch.yml:
cluster.name: production
node.name: node1
network.host: 0.0.0.0
transport.tcp.port: 9300
cluster.initial_master_nodes: node1
Setup:
client = new PreBuiltTransportClient(Settings.builder().put("cluster.name", "production").build());
client.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300));
Since PreBuiltTransportClient is deprecated you should use RestHighLevelClient for Elasticsearch-Version 7.3.0: https://artifacts.elastic.co/javadoc/org/elasticsearch/client/elasticsearch-rest-high-level-client/7.3.0/index.html
I spent ages trying to figure this out but it is simple! You can use length(·)
. length(mylist)
will tell you the number of objects mylist
contains.
... and just realised someone had already answered this- sorry!
Map:- This method takes one Function as an argument and returns a new stream consisting of the results generated by applying the passed function to all the elements of the stream.
Let's imagine, I have a list of integer values ( 1,2,3,4,5 ) and one function interface whose logic is square of the passed integer. ( e -> e * e ).
List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> newList = intList.stream().map( e -> e * e ).collect(Collectors.toList());
System.out.println(newList);
output:-
[1, 4, 9, 16, 25]
As you can see, an output is a new stream whose values are square of values of the input stream.
[1, 2, 3, 4, 5] -> apply e -> e * e -> [ 1*1, 2*2, 3*3, 4*4, 5*5 ] -> [1, 4, 9, 16, 25 ]
http://codedestine.com/java-8-stream-map-method/
FlatMap :- This method takes one Function as an argument, this function accepts one parameter T as an input argument and returns one stream of parameter R as a return value. When this function is applied to each element of this stream, it produces a stream of new values. All the elements of these new streams generated by each element are then copied to a new stream, which will be a return value of this method.
Let's image, I have a list of student objects, where each student can opt for multiple subjects.
List<Student> studentList = new ArrayList<Student>();
studentList.add(new Student("Robert","5st grade", Arrays.asList(new String[]{"history","math","geography"})));
studentList.add(new Student("Martin","8st grade", Arrays.asList(new String[]{"economics","biology"})));
studentList.add(new Student("Robert","9st grade", Arrays.asList(new String[]{"science","math"})));
Set<Student> courses = studentList.stream().flatMap( e -> e.getCourse().stream()).collect(Collectors.toSet());
System.out.println(courses);
output:-
[economics, biology, geography, science, history, math]
As you can see, an output is a new stream whose values are a collection of all the elements of the streams return by each element of the input stream.
[ S1 , S2 , S3 ] -> [ {"history","math","geography"}, {"economics","biology"}, {"science","math"} ] -> take unique subjects -> [economics, biology, geography, science, history, math]
The key elements include:
class="nav nav-tabs"
and data-tabs="tabs"
of ul
data-toggle="tab"
and href="#orange"
of the a
class="tab-content"
of the div
of the contentclass="tab-pane"
and id
of the div of the itemsThe complete code is as below:
<ul class="nav nav-tabs" data-tabs="tabs">
<li class="active"><a data-toggle="tab" href="#red">Red</a></li>
<li><a data-toggle="tab" href="#orange">Orange</a></li>
<li><a data-toggle="tab" href="#yellow">Yellow</a></li>
<li><a data-toggle="tab" href="#green">Green</a></li>
<li><a data-toggle="tab" href="#blue">Blue</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="red">
<h1>Red</h1>
<p>red red red red red red</p>
</div>
<div class="tab-pane" id="orange">
<h1>Orange</h1>
<p>orange orange orange orange orange</p>
</div>
<div class="tab-pane" id="yellow">
<h1>Yellow</h1>
<p>yellow yellow yellow yellow yellow</p>
</div>
<div class="tab-pane" id="green">
<h1>Green</h1>
<p>green green green green green</p>
</div>
<div class="tab-pane" id="blue">
<h1>Blue</h1>
<p>blue blue blue blue blue</p>
</div>
</div>
To call a python function from Jinja2, you can use custom filters which work similarly as the globals: http://jinja.pocoo.org/docs/dev/api/#writing-filters
It's quite simple and useful. In a file myTemplate.txt, I wrote:
{{ data|pythonFct }}
And in a python script:
import jinja2
def pythonFct(data):
return "This is my data: {0}".format(data)
input="my custom filter works!"
loader = jinja2.FileSystemLoader(path or './')
env = jinja2.Environment(loader=loader)
env.filters['pythonFct'] = pythonFct
result = env.get_template("myTemplate.txt").render(data=input)
print(result)
return None
or return
can be used to exit out of a function or program, both does the same thingquit()
function can be used, although use of this function is discouraged for making real world applications and should be used only in interpreter. import site
def func():
print("Hi")
quit()
print("Bye")
exit()
function can be used, similar to quit()
but the use is discouraged for making real world applications.import site
def func():
print("Hi")
exit()
print("Bye")
sys.exit([arg])
function can be used and need to import sys
module for that, this function can be used for real world applications unlike the other two functions.import sys
height = 150
if height < 165: # in cm
# exits the program
sys.exit("Height less than 165")
else:
print("You ride the rollercoaster.")
os._exit(n)
function can be used to exit from a process, and need to import os
module for that.Granted, there are definitely different thinking, in my world, I cannot enforce "Never pass a null" because I am dealing with uncontrollable third parties like API callers, database records, former programmers etc... so I am paranoid and defensive in approaches. Since you are on Java8 or later there is a bit cleaner approach than an if
block.
public String foo(@Nullable String mayBeNothing) {
return Optional.ofNullable(mayBeNothing).orElse("Really Nothing");
}
You can also throw some exception in there by swapping .orElse
to
orElseThrow(() -> new Exception("Dont' send a null"))
.
If you don't want to use @Nullable, which adds nothing functionally, why not just name the parameter with mayBe...
so your intention is clear.
No, there is no way to specify defaults. I believer this is done on purpose to enhance readability, at the cost of a little more time (and, hopefully, thought) on the writer's end.
I think the proper approach to having a "default" is to have a new function which supplies that default to the more generic function. Having this, your code becomes clearer on your intent. For example:
func SaySomething(say string) {
// All the complicated bits involved in saying something
}
func SayHello() {
SaySomething("Hello")
}
With very little effort, I made a function that does a common thing and reused the generic function. You can see this in many libraries, fmt.Println
for example just adds a newline to what fmt.Print
would otherwise do. When reading someone's code, however, it is clear what they intend to do by the function they call. With default values, I won't know what is supposed to be happening without also going to the function to reference what the default value actually is.
This could be due running wrong scheme as well.
You may check *spell
en-GB dictionary used by Mozilla, OpenOffice, plenty of other software.
Change your jQuery code with this. It will alert the id of the a.
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
markActiveLink();
alert('123');
});
function markActiveLink(el) {
var el = $('a').attr("id")
alert(el);
}
SELECT created
FROM dba_objects
WHERE object_name = <<your table name>>
AND owner = <<owner of the table>>
AND object_type = 'TABLE'
will tell you when a table was created (if you don't have access to DBA_OBJECTS, you could use ALL_OBJECTS instead assuming you have SELECT privileges on the table).
The general answer to getting timestamps from a row, though, is that you can only get that data if you have added columns to track that information (assuming, of course, that your application populates the columns as well). There are various special cases, however. If the DML happened relatively recently (most likely in the last couple hours), you should be able to get the timestamps from a flashback query. If the DML happened in the last few days (or however long you keep your archived logs), you could use LogMiner to extract the timestamps but that is going to be a very expensive operation particularly if you're getting timestamps for many rows. If you build the table with ROWDEPENDENCIES enabled (not the default), you can use
SELECT scn_to_timestamp( ora_rowscn ) last_modified_date,
ora_rowscn last_modified_scn,
<<other columns>>
FROM <<your table>>
to get the last modification date and SCN (system change number) for the row. By default, though, without ROWDEPENDENCIES, the SCN is only at the block level. The SCN_TO_TIMESTAMP
function also isn't going to be able to map SCN's to timestamps forever.
I had this problem after changing the password for the root user in phpMyAdmin. I know nothing about programming but I solved it by doing the following:
Go to file C:\wamp\apps\phpmyadmin3.2.0.1\config.inc.php
(I guess you would replace "wamp" with the name of your server if you're not using Wamp Server)
Find the line $cfg['Servers'][$i]['password']=''
and change this to
$cfg['Servers'][$i]['password']='NO'
Try opening phpMyAdmin again, and hopefully the message will now read "Access denied for user 'root'@'localhost' (using password: YES)
Now change the password in the above line to 'yourpassword' (whatever you had set it to before)
Hope this helps somebody.
<select ng-model="divs" ng-options="(d.group+' - '+d.sub) for d in divisions | orderBy:['group','sub']" />
User array instead of multiple orderBY
FYI: In .NET, Hashtable
is thread safe for use by multiple reader threads and a single writing thread, while in Dictionary
public static members are thread safe, but any instance members are not guaranteed to be thread safe.
We had to change all our Dictionaries back to Hashtable
because of this.
This piece of code is incorrect.
while 1:
(clientsocket, address) = serversocket.accept()
print ("connection found!")
data = clientsocket.recv(1024).decode()
print (data)
r='REceieve'
clientsocket.send(r.encode())
The call on accept()
on the serversocket
blocks until there's a client connection. When you first connect to the server from the client, it accepts the connection and receives data. However, when it enters the loop again, it is waiting for another connection and thus blocks as there are no other clients that are trying to connect.
That's the reason the recv
works correct only the first time. What you should do is find out how you can handle the communication with a client that has been accepted - maybe by creating a new Thread to handle communication with that client and continue accepting new clients in the loop, handling them in the same way.
Tip: If you want to work on creating your own chat application, you should look at a networking engine like Twisted. It will help you understand the whole concept better too.
For me personally the main attraction of OOP programming is the ability to have self-contained classes with unexposed (private) inner workings.
What confuses me to no end in Javascript is that you can't even use function names, because you run the risk of having that same function name somewhere else in any of the external libraries that you're using.
Even though some very smart people have found workarounds for this, isn't it weird that Javascript in its purest form requires you to create code that is highly unreadable?
The beauty of OOP is that you can spend your time thinking about your app's logic, without having to worry about syntax.
I think this could be done in a much simpler way:
So code would look something like this:
WebElement month = driver.findElement(month combo locator);
Select monthCombo = new Select(month);
monthCombo.selectByVisibleText("March");
WebElement year = driver.findElement(year combo locator);
Select yearCombo = new Select(year);
yearCombo.selectByVisibleText("2015");
driver.click(By.linkText("31"));
This won't work if the date picker dropdowns are not Select, but most of the ones I've seen are individual elements (select, links, etc.)
The best form is this
$('#example option').length
In DOS you couldn't use environment variables on the command line, only in batch files, where they used the %
sign as a delimiter. If you wanted a literal %
sign in a batch file, e.g. in an echo
statement, you needed to double it.
This carried over to Windows NT which allowed environment variables on the command line, however for backwards compatibility you still need to double your %
signs in a .cmd file.
The only way that I know that enables you to use ajax cross-domain is JSONP (http://ajaxian.com/archives/jsonp-json-with-padding).
And here's a post that posts some various techniques to achieve cross-domain ajax (http://usejquery.com/posts/9/the-jquery-cross-domain-ajax-guide)
Just found that lines below must be added to web.config
file, now everything works fine on production server too.
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" >
<remove name="UrlRoutingModule"/>
</modules>
</system.webServer>
Update: In the past few years the landscape has changed drastically. You can now reliably use querySelector
and querySelectorAll
, see Wojtek's answer for how to do this.
There's no need for a jQuery dependency now. If you're using jQuery, great...if you're not, you need not rely it on just for selecting elements by attributes anymore.
There's not a very short way to do this in vanilla javascript, but there are some solutions available.
You do something like this, looping through elements and checking the attribute
If a library like jQuery is an option, you can do it a bit easier, like this:
$("[myAttribute=value]")
If the value isn't a valid CSS identifier (it has spaces or punctuation in it, etc.), you need quotes around the value (they can be single or double):
$("[myAttribute='my value']")
You can also do start-with
, ends-with
, contains
, etc...there are several options for the attribute selector.
If you are testing your app on actual device then you can try this small android app which gives you the device id:
https://play.google.com/store/apps/details?id=pe.go_com.admobdeviceidfinder&hl=en
You will get the hashed device id directly. Hope this helps.
this article saved my day: https://bewilderedoctothorpe.net/2018/12/21/out-of-inodes/
find . -maxdepth 1 -type d | grep -v '^\.$' | xargs -n 1 -i{} find {} -xdev -type f | cut -d "/" -f 2 | uniq -c | sort -n
Simply try this for all properties of an object,
foreach (var prop in myobject.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance))
{
var propertyName = prop.Name;
var propertyValue = myobject.GetType().GetProperty(propertyName).GetValue(myobject, null);
//Debug.Print(prop.Name);
//Debug.Print(Functions.convertNullableToString(propertyValue));
Debug.Print(string.Format("Property Name={0} , Value={1}", prop.Name, Functions.convertNullableToString(propertyValue)));
}
NOTE: Functions.convertNullableToString() is custom function using for convert NULL value into string.empty.
Wrapping the model property around parens worked for me. You still get the same issue with Visual Studio complaining about the semi-colon, but it works.
var closedStatusId = @(Model.ClosedStatusId);
Swift4
@IBOutlet weak var actionButton: UIButton!
@IBOutlet weak var timeLabel: UILabel!
var timer:Timer?
var timeLeft = 60
override func viewDidLoad() {
super.viewDidLoad()
setupTimer()
}
func setupTimer() {
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(onTimerFires), userInfo: nil, repeats: true)
}
@objc func onTimerFires() {
timeLeft -= 1
timeLabel.text = "\(timeLeft) seconds left"
if timeLeft <= 0 {
actionButton.isEnabled = true
actionButton.setTitle("enabled", for: .normal)
timer?.invalidate()
timer = nil
}
}
@IBAction func btnClicked(_ sender: UIButton) {
print("API Fired")
}
$date = strtotime('2016-2-3');
$date = date('l', $date);
var_dump($date)
(i added format 'l' so it will return full name of day)
You could set the width of the abbrev column to a fixed pixel width, then set the width of the description column to the width of the DataGridView, minus the sum of the widths of the other columns and some extra margin (if you want to prevent a horizontal scrollbar from appearing on the DataGridView):
dataGridView1.Columns[1].Width = 108; // or whatever width works well for abbrev
dataGridView1.Columns[2].Width =
dataGridView1.Width
- dataGridView1.Columns[0].Width
- dataGridView1.Columns[1].Width
- 72; // this is an extra "margin" number of pixels
If you wanted the description column to always take up the "remainder" of the width of the DataGridView, you could put something like the above code in a Resize
event handler of the DataGridView.
you are almost there; you just need to give the reference to master; since you want to get the file from the master branch:
git checkout master -- filename
Note that the differences will be cached; so if you want to see the differences you obtained; use
git diff --cached
If you want to redirect a whole subfolder, the url
argument in RedirectView is actually interpolated, so you can do something like this in urls.py
:
from django.conf.urls.defaults import url
from django.views.generic import RedirectView
urlpatterns = [
url(r'^old/(?P<path>.*)$', RedirectView.as_view(url='/new_path/%(path)s')),
]
The ?P<path>
you capture will be fed into RedirectView
. This captured variable will then be replaced in the url
argument you gave, giving us /new_path/yay/mypath
if your original path was /old/yay/mypath
.
You can also do ….as_view(url='…', query_string=True)
if you want to copy the query string over as well.
vs2015 no enable nuget restore problem. My solution:
add folder .nuget, add file NuGet.Config and NuGet.targets in Directory .nuget
each project file add: build
<RestorePackages>true</RestorePackages>
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
something like:
$('#doc').click(function(e){
e.preventDefault()
e.stopImmediatePropagation() //charles ma is right about that, but stopPropagation isn't also needed
});
should do the job you could also bind more mouse events with replacing for: edit: add this in the feezing part
$('#doc').bind('click mousedown dblclick',function(e){
e.preventDefault()
e.stopImmediatePropagation()
});
and this in the unfreezing:
$('#doc').unbind();
A quick guess if you post your code can say for sure but you might have done something along the lines of
HashMap<String, Object> test = new HashMap();
which will produce the warning when you need to do
HashMap<String, Object> test = new HashMap<String, Object>();
it might be worth looking at
Generics in the Java Programming Language
if your unfamiliar with what needs to be done.
SELECT <...>
FROM A.tableA JOIN B.tableB
If you want to refer to names from the header rather than column numbers, you can use something like this:
fname <- "test.csv"
headset <- read.csv(fname, header = TRUE, nrows = 10)
classes <- sapply(headset, class)
classes[names(classes) %in% c("time")] <- "character"
dataset <- read.csv(fname, header = TRUE, colClasses = classes)
"This is a comment in vimrc. It does not have a closing quote
Source: http://vim.wikia.com/wiki/Backing_up_and_commenting_vimrc
The names and values are confusing. If you are looking for the total free memory you will have to calculate this value by your self. It is not what you get from freeMemory();
.
See the following guide:
Total designated memory, this will equal the configured -Xmx value:
Runtime.getRuntime().maxMemory();
Current allocated free memory, is the current allocated space ready for new objects. Caution this is not the total free available memory:
Runtime.getRuntime().freeMemory();
Total allocated memory, is the total allocated space reserved for the java process:
Runtime.getRuntime().totalMemory();
Used memory, has to be calculated:
usedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
Total free memory, has to be calculated:
freeMemory = Runtime.getRuntime().maxMemory() - usedMemory;
A picture may help to clarify:
Loads of answers here, but haven't seen the one I use:
input[type="text"]:read-only { color: blue; }
Note the dash in the pseudo selector. If the input is readonly="false"
it'll catch that too since this selector catches the presence of readonly regardless of the value. Technically false
is invalid according to specs, but the internet is not a perfect world. If you need to cover that case, you can do this:
input[type="text"]:read-only:not([read-only="false"]) { color: blue; }
textarea
works the same way:
textarea:read-only:not([read-only="false"]) { color: blue; }
Keep in mind that html now supports not only type="text"
, but a slew of other textual types such a number
, tel
, email
, date
, time
, url
, etc. Each would need to be added to the selector.
Since the other answers explained how to do it without actually explaining why it works:
When the switch
executes, it finds the first matching case
statement and then executes each line of code after the switch until it hits either a break
statement or the end of the switch
(or a return
statement to leave the entire containing function). When you deliberately omit the break
so that code under the next case
gets executed too that's called a fall-through. So for the OP's requirement:
switch (pageid) {
case "listing-page":
case "home-page":
alert("hello");
break;
case "details-page":
alert("goodbye");
break;
}
Forgetting to include break
statements is a fairly common coding mistake and is the first thing you should look for if your switch
isn't working the way you expected. For that reason some people like to put a comment in to say "fall through" to make it clear when break statements have been omitted on purpose. I do that in the following example since it is a bit more complicated and shows how some cases can include code to execute before they fall-through:
switch (someVar) {
case 1:
someFunction();
alert("It was 1");
// fall through
case 2:
alert("The 2 case");
// fall through
case 3:
// fall through
case 4:
// fall through
case 5:
alert("The 5 case");
// fall through
case 6:
alert("The 6 case");
break;
case 7:
alert("Something else");
break;
case 8:
// fall through
default:
alert("The end");
break;
}
You can also (optionally) include a default
case, which will be executed if none of the other cases match - if you don't include a default
and no cases match then nothing happens. You can (optionally) fall through to the default case.
So in my second example if someVar
is 1 it would call someFunction()
and then you would see four alerts as it falls through multiple cases some of which have alerts under them. Is someVar
is 3, 4 or 5 you'd see two alerts. If someVar
is 7 you'd see "Something else" and if it is 8 or any other value you'd see "The end".
Sure you can. Something like:
HTML
<div ng-controller="fessCntrl">
<label ng-repeat="(key,val) in list">
<input type="radio" name="localityTypeRadio" ng-model="$parent.localityTypeRadio" ng-value="key" />{{key}}
<div ng-if="key == 'City' || key == 'County'">
<pre>City or County !!! {{$parent.localityTypeRadio}}</pre>
</div>
<div ng-if="key == 'Town'">
<pre>Town!!! {{$parent.localityTypeRadio}}</pre>
</div>
</label>
</div>
JS
var fessmodule = angular.module('myModule', []);
fessmodule.controller('fessCntrl', function ($scope) {
$scope.list = {
City: [{name: "cityA"}, {name: "cityB"}],
County: [{ name: "countyA"}, {name: "countyB"}],
Town: [{ name: "townA"}, {name: "townB"}]
};
$scope.localityTypeRadio = 'City';
});
fessmodule.$inject = ['$scope'];
Demo Fiddle
It also posible string replacement with stringByReplacingCharactersInRange:withString:
for (int i = 0; i < card.length - 4; i++) {
if (![[card substringWithRange:NSMakeRange(i, 1)] isEqual:@" "]) {
NSRange range = NSMakeRange(i, 1);
card = [card stringByReplacingCharactersInRange:range withString:@"*"];
}
} //out: **** **** **** 1234
It took me sometime to figure out fix from given answers, due to my newbieness. This is what I came up with, if anyone else needs help from the very beginning:
import org.apache.spark.SparkContext
import org.apache.spark.SparkConf
object MyObject {
def main(args: Array[String]): Unit = {
val mySparkConf = new SparkConf().setAppName("SparkApp").setMaster("local[*]").set("spark.executor.memory","5g");
val sc = new SparkContext(mySparkConf)
val conf = sc.hadoopConfiguration
conf.set("fs.hdfs.impl", classOf[org.apache.hadoop.hdfs.DistributedFileSystem].getName)
conf.set("fs.file.impl", classOf[org.apache.hadoop.fs.LocalFileSystem].getName)
I am using Spark 2.1
And I have this part in my build.sbt
assemblyMergeStrategy in assembly := {
case PathList("META-INF", xs @ _*) => MergeStrategy.discard
case x => MergeStrategy.first
}
Client send some messages need be compressed, server (kafka) decompress the string meesage
Below is my sample:
compress:
public static String compress(String str, String inEncoding) {
if (str == null || str.length() == 0) {
return str;
}
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes(inEncoding));
gzip.close();
return URLEncoder.encode(out.toString("ISO-8859-1"), "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
decompress:
public static String decompress(String str, String outEncoding) {
if (str == null || str.length() == 0) {
return str;
}
try {
String decode = URLDecoder.decode(str, "UTF-8");
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(decode.getBytes("ISO-8859-1"));
GZIPInputStream gunzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = gunzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
return out.toString(outEncoding);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
ART
According to the docs: http://web.archive.org/web/20170909233829/https://source.android.com/devices/tech/dalvik/configure an .odex
file:
contains AOT compiled code for methods in the APK.
Furthermore, they appear to be regular shared libraries, since if you get any app, and check:
file /data/app/com.android.appname-*/oat/arm64/base.odex
it says:
base.odex: ELF shared object, 64-bit LSB arm64, stripped
and aarch64-linux-gnu-objdump -d base.odex
seems to work and give some meaningful disassembly (but also some rubbish sections).
You can do this as:
WITH abc AS( select
FROM ...)
, XYZ AS(select
From abc ....) /*This one uses "abc" multiple times*/
Select
From XYZ.... /*using abc, XYZ multiple times*/
well, there was 2 issues: 1.instead of pip, pip3 should be used. 2.its better to use virtual env. because i have had multiple python version installed
I had the same problem but solved it running following:
$ adb shell
$ run-as {app-package-name}
$ cd /data/data/{app-package-name}
$ chmod 777 {file}
$ cp {file} /mnt/sdcard/
After this you can run
$ adb pull /mnt/sdcard/{file}