When you include jQuery the first time:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
The second script plugs itself into jQuery, and "adds" $(...).datepicker
.
But then you are including jQuery once again:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
It undoes the plugging in and therefore $(...).datepicker
becomes undefined.
Although the first $(document).ready
block appears before that, the anonymous callback function body is not executed until all scripts are loaded, and by then $(...)
(window.$
to be precise) is referring to the most recently loaded jQuery.
You would not run into this if you called $('.dateinput').datepicker
immediately rather than in $(document).ready
callback, but then you'd need to make sure that the target element (with class dateinput
) is already in the document before the script, and it's generally advised to use the ready
callback.
If you want to use datepicker
from jquery-ui, it would probably make most sense to include the jquery-ui script after bootstrap. jquery-ui 1.11.4 is compatible with jquery 1.6+ so it will work fine.
Alternatively (in particular if you are not using jquery-ui for anything else), you could try bootstrap-datepicker.
In order to accomplish this, it is best to design fragment construct to receive that data and save that data in its bundle arguments.
class FragmentA extends Fragment{
public static FragmentA newInstance(YourDataClass data) {
FragmentA f = new FragmentA();
Bundle b = new Bundle();
b.putString("data", data);
f.setArguments(b);
return f;
}
}
In order to start the fragment from the class, you can do the following
Fragment newFragment = FragmentA.newInstance(objectofyourclassdata);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
However, the data class must be parceable or serializable.
For full information on fragments and best practices on use of fragments, please spend some time on official docs, it is super useful, at least my experience
https://developer.android.com/guide/components/fragments#java
you can use LayoutInflater to inflate your dynamic data as a layout file.
UPDATE : first create a LinearLayout inside your CardView's layout and assign an ID for it.
after that create a layout file that you want to inflate. at last in your onBindViewHolder
method in your "RAdaper" class. write these codes :
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = mInflater.inflate(R.layout.my_list_custom_row, parent, false);
after that you can initialize data and ClickListeners with your RAdapter Data. hope it helps.
I got the same problem and its all snatching my hair. Thanks for this https://stackoverflow.com/a/35697105/5228412
What we can do..
favourite_fab.setImageDrawable(ContextCompat.getDrawable(getBaseContext(), R.drawable.favourite_selected));
it works fine for me and wish for others who'll reach here.
Don't use jsonObject.toString
on a JSON object.
If you are sure you haven't messed the jar, then please clean the project and perform mvn clean install
. This should solve the problem.
If you read this, it's probably because all the previous answers didn't work for your Holo Dark based theme.
Holo Dark uses an additional wrapper for the PopupMenus, so after doing what Jonik suggested you have to add the following style to your 'xml' file:
<style name="PopupWrapper" parent="@android:style/Theme.Holo">
<item name="android:popupMenuStyle">@style/YourPopupMenu</item>
</style>
Then reference it in your theme block:
<style name="Your.cool.Theme" parent="@android:style/Theme.Holo">
.
.
.
<item name="android:actionBarWidgetTheme">@style/PopupWrapper</item>
</style>
That's it!
This question is a old one but it can help for others too.
Try this :
li.setBackgroundColor(getResources().getColor(R.color.blue));
or
li.setBackgroundColor(getResources().getColor(android.R.color.red));
or
li.setBackgroundColor(Color.rgb(226, 11, 11));
or
li.setBackgroundColor(Color.RED)
I believe the browser is looking for those assets FROM the root of the webserver. This is difficult because it is easy to start developing on your machine WITHOUT actually using a webserver ( just by loading local files through your browser)
You could start by packaging your html and css/js together?
a directory structure something like:
-yourapp
- index.html
- assets
- css
- js
- myPage.js
Then your script tag (from index.html) could look like
<script src="assets/js/myPage.js"></script>
An added benifit of packaging your html and assets in one directory is that you can copy the directory and give it to someone else or put it on another machine and it will work great.
My way of achieving this is by creating ZipInputStream wrapping class that would handle that would provide only the stream of current entry:
The wrapper class:
public class ZippedFileInputStream extends InputStream {
private ZipInputStream is;
public ZippedFileInputStream(ZipInputStream is){
this.is = is;
}
@Override
public int read() throws IOException {
return is.read();
}
@Override
public void close() throws IOException {
is.closeEntry();
}
}
The use of it:
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream("SomeFile.zip"));
while((entry = zipInputStream.getNextEntry())!= null) {
ZippedFileInputStream archivedFileInputStream = new ZippedFileInputStream(zipInputStream);
//... perform whatever logic you want here with ZippedFileInputStream
// note that this will only close the current entry stream and not the ZipInputStream
archivedFileInputStream.close();
}
zipInputStream.close();
One advantage of this approach: InputStreams are passed as an arguments to methods that process them and those methods have a tendency to immediately close the input stream after they are done with it.
A reset will normally change everything, but you can use git stash
to pick what you want to keep. As you mentioned, stash
doesn't accept a path directly, but it can still be used to keep a specific path with the --keep-index
flag. In your example, you would stash the b directory, then reset everything else.
# How to make files a/* reappear without changing b and without recreating a/c?
git add b #add the directory you want to keep
git stash --keep-index #stash anything that isn't added
git reset #unstage the b directory
git stash drop #clean up the stash (optional)
This gets you to a point where the last part of your script will output this:
After checkout:
# On branch master
# Changes not staged for commit:
#
# modified: b/a/ba
#
no changes added to commit (use "git add" and/or "git commit -a")
a/a/aa
a/b/ab
b/a/ba
I believe this was the target result (b remains modified, a/* files are back, a/c is not recreated).
This approach has the added benefit of being very flexible; you can get as fine-grained as you want adding specific files, but not other ones, in a directory.
Reading a CSV file in very simple and common in Java. You actually don't require to load any extra third party library to do this for you. CSV (comma separated value) file is just a normal plain-text file, store data in column by column, and split it by a separator (e.g comma ",").
In order to read specific columns from the CSV file, there are several ways. Simplest of all is as below:
Code to read CSV without any 3rd party library
BufferedReader br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] cols = line.split(cvsSplitBy);
System.out.println("Coulmn 4= " + cols[4] + " , Column 5=" + cols[5]);
}
If you notice, nothing special is performed here. It is just reading a text file, and spitting it by a separator ā ",".
Consider an extract from legacy country CSV data at GeoLite Free Downloadable Databases
"1.0.0.0","1.0.0.255","16777216","16777471","AU","Australia"
"1.0.1.0","1.0.3.255","16777472","16778239","CN","China"
"1.0.4.0","1.0.7.255","16778240","16779263","AU","Australia"
"1.0.8.0","1.0.15.255","16779264","16781311","CN","China"
"1.0.16.0","1.0.31.255","16781312","16785407","JP","Japan"
"1.0.32.0","1.0.63.255","16785408","16793599","CN","China"
"1.0.64.0","1.0.127.255","16793600","16809983","JP","Japan"
"1.0.128.0","1.0.255.255","16809984","16842751","TH","Thailand"
Above code will output as below:
Column 4= "AU" , Column 5="Australia"
Column 4= "CN" , Column 5="China"
Column 4= "AU" , Column 5="Australia"
Column 4= "CN" , Column 5="China"
Column 4= "JP" , Column 5="Japan"
Column 4= "CN" , Column 5="China"
Column 4= "JP" , Column 5="Japan"
Column 4= "TH" , Column 5="Thailand"
You can, in fact, put
the columns in a Map
and then get the values simply by using the key
.
Shishir
This is your config :
log4j.appender.FILE.File=logs/${file.name}
And this error happened :
java.io.FileNotFoundException: logs (Access is denied)
So it seems that the variable file.name
is not set, and java tries to write to the directory logs
.
You can force the value of your variable ${file.name}
calling maven with this option -D :
mvn clean test -Dfile.name=logfile.log
@MaxPython The answer above is missing ":"
try:
#do something
except:
# print 'error/exception'
def printError(e): print e
1.Set the following Environment Property on your active Shell. - open bash terminal and type in:
$ export LD_BIND_NOW=1
Note: for superuser in bash type su and press enter
Sadly none of the above worked for me so I spent very long time trying different combination of sparse-checkout
file.
In my case I wanted to skip folders with IntelliJ IDEA configs.
Here is what I did:
Run git clone https://github.com/myaccount/myrepo.git --no-checkout
Run git config core.sparsecheckout true
Created .git\info\sparse-checkout
with following content
!.idea/*
!.idea_modules/*
/*
Run 'git checkout --' to get all files.
Critical thing to make it work was to add /*
after folder's name.
I have git 1.9
I have just discovered a plugin on JSFiddle. Two possible alternatives : 1 single input OR 3 inputs, but looks like a single one... (use Tab key to go to the next input)
[link]http://jsfiddle.net/davidelrizzo/c8ASE/ It seems interesting !
marks = raw_input('Enter your Obtain marks:')
outof = raw_input('Enter Out of marks:')
marks = int(marks)
outof = int(outof)
per = marks*100/outof
print 'Your Percentage is:'+str(per)
Note : raw_input() function is used to take input from console and its return string formatted value. So we need to convert into integer otherwise it give error of conversion.
It points to the docker host! I followed these steps:
$ boot2docker start
Waiting for VM and Docker daemon to start...
..............................
Started.
To connect the Docker client to the Docker daemon, please set:
export DOCKER_HOST=tcp://192.168.59.103:2375
$ export DOCKER_HOST=tcp://192.168.59.103:2375
$ docker run ubuntu:14.04 /bin/echo 'Hello world'
Unable to find image 'ubuntu:14.04' locally
Pulling repository ubuntu
9cbaf023786c: Download complete
511136ea3c5a: Download complete
97fd97495e49: Download complete
2dcbbf65536c: Download complete
6a459d727ebb: Download complete
8f321fc43180: Download complete
03db2b23cf03: Download complete
Hello world
I have custom loading. Properties must be defined as:
key.0=value0
key.1=value1
...
Custom loading:
/** Return array from properties file. Array must be defined as "key.0=value0", "key.1=value1", ... */
public List<String> getSystemStringProperties(String key) {
// result list
List<String> result = new LinkedList<>();
// defining variable for assignment in loop condition part
String value;
// next value loading defined in condition part
for(int i = 0; (value = YOUR_PROPERTY_OBJECT.getProperty(key + "." + i)) != null; i++) {
result.add(value);
}
// return
return result;
}
I had a similar issue when I tried to run a project. First i uninstalled the current version
npm uninstall node-sass
Then i reinstalled to the latest version with
npm install node-sass
CGSize maximumLabelSize = CGSizeMake(label.frame.size.width, FLT_MAX);
CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];
float heightUse = expectedLabelSize.height;
I find HttpURLConnection
really cumbersome to use. And you have to write a lot of boilerplate, error prone code. I needed a lightweight wrapper for my Android projects and came out with a library which you can use as well: DavidWebb.
The above example could be written like this:
Webb webb = Webb.create();
webb.post("http://example.com/index.php")
.param("param1", "a")
.param("param2", "b")
.param("param3", "c")
.ensureSuccess()
.asVoid();
You can find a list of alternative libraries on the link provided.
%d
and %s
are placeholders, they work as a replaceable variable. For example, if you create 2 variables
variable_one = "Stackoverflow"
variable_two = 45
you can assign those variables to a sentence in a string using a tuple of the variables.
variable_3 = "I was searching for an answer in %s and found more than %d answers to my question"
Note that %s
works for String and %d
work for numerical or decimal variables.
if you print variable_3
it would look like this
print(variable_3 % (variable_one, variable_two))
I was searching for an answer in StackOverflow and found more than 45 answers to my question.
Add below event to DateTimePicker
Private Sub DateTimePicker1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles DateTimePicker1.KeyPress
e.Handled = True
End Sub
I think, better way is use HttpPostedFileBase in your controller or API. After this you can simple detect size, type etc.
File properties you can find here:
MVC3 How to check if HttpPostedFileBase is an image
For example ImageApi:
[HttpPost]
[Route("api/image")]
public ActionResult Index(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
try
{
string path = Path.Combine(Server.MapPath("~/Images"),
Path.GetFileName(file.FileName));
file.SaveAs(path);
ViewBag.Message = "Your message for success";
}
catch (Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
else
{
ViewBag.Message = "Please select file";
}
return View();
}
Hope it help.
In simpler words:
key=
parameter of sort
requires a key function (to be applied to be objects to be sorted) rather than a single key value and operator.itemgetter(1)
will give you: A function that grabs the first item from a list-like object. (More precisely those are callables, not functions, but that is a difference that can often be ignored.)
I wrote a shell function for a similar use case I encounter daily on projects. This is basically a shortcut for keeping local branches up to date with a common branch like develop before opening a PR, etc.
Posting this even though you don't want to use
checkout
, in case others don't mind that constraint.
glmh
("git pull and merge here") will automatically checkout branchB
, pull
the latest, re-checkout branchA
, and merge branchB
.
Doesn't address the need to keep a local copy of branchA, but could easily be modified to do so by adding a step before checking out branchB. Something like...
git branch ${branchA}-no-branchB ${branchA}
For simple fast-forward merges, this skips to the commit message prompt.
For non fast-forward merges, this places your branch in the conflict resolution state (you likely need to intervene).
.bashrc
or .zshrc
, etc:glmh() {
branchB=$1
[ $# -eq 0 ] && { branchB="develop" }
branchA="$(git branch | grep '*' | sed 's/* //g')"
git checkout ${branchB} && git pull
git checkout ${branchA} && git merge ${branchB}
}
# No argument given, will assume "develop"
> glmh
# Pass an argument to pull and merge a specific branch
> glmh your-other-branch
Note: This is not robust enough to hand-off of args beyond branch name to
git merge
This is how I do it...
public class ThreadA {
public ThreadA(object[] args) {
...
}
public void Run() {
while (true) {
Thread.sleep(1000); // wait 1 second for something to happen.
doStuff();
if(conditionToExitReceived) // what im waiting for...
break;
}
//perform cleanup if there is any...
}
}
Then to run this in its own thread... ( I do it this way because I also want to send args to the thread)
private void FireThread(){
Thread thread = new Thread(new ThreadStart(this.startThread));
thread.start();
}
private void (startThread){
new ThreadA(args).Run();
}
The thread is created by calling "FireThread()"
The newly created thread will run until its condition to stop is met, then it dies...
You can signal the "main" with delegates, to tell it when the thread has died.. so you can then start the second one...
Best to read through : This MSDN Article
Using some of the answers on this page and here, I came up with my own answer as none of these answers fully solved it for me.
Here is crux of it
var startDate = "27 Apr 2017";
var numOfYears = 1;
var expireDate = new Date(startDate);
expireDate.setFullYear(expireDate.getFullYear() + numOfYears);
expireDate.setDate(expireDate.getDate() -1);
And here a a JSFiddle that has a working example: https://jsfiddle.net/wavesailor/g9a6qqq5/
Checked solution is not accurate, sometimes mouse-right-click triggers right-swipe. after trying different plugins for swipe i found an almost perfect one.
i said "almost" because this plugin does not support future elements. so we would have to reinitialize the swipe call when the swipe content is changed by ajax or something. this plugin have lots of options to play with touch events like multi-finger-touch,pinch etc.
http://labs.rampinteractive.co.uk/touchSwipe/demos/index.html
$("#myCarousel").swipe( {
swipe:function(event, direction, distance, duration, fingerCount, fingerData) {
if(direction=='left'){
$(this).carousel('next');
}else if(direction=='right'){
$(this).carousel('prev');
}
}
});
function addSwipeTo(selector){
$(selector).swipe("destroy");
$(selector).swipe( {
swipe:function(event, direction, distance, duration, fingerCount, fingerData) {
if(direction=='left'){
$(this).carousel('next');
}else if(direction=='right'){
$(this).carousel('prev');
}
}
});
}
addSwipeTo("#myCarousel");
Perhaps a good idea is to use jQuery in this case. It provides handy functionality and you can do things like this:
$('div').html('<b>Test</b>');
Take a look at http://docs.jquery.com/Attributes/html#val for more information.
I think you're looking for;
string[] skus = myLines.Select(x => x.Sku).ToArray();
However, if you're going to iterate over the sku's in subsequent code I recommend not using the ToArray()
bit as it forces the queries execution prematurely and makes the applications performance worse. Instead you can just do;
var skus = myLines.Select(x => x.Sku); // produce IEnumerable<string>
foreach (string sku in skus) // forces execution of the query
If all you need is a user provided dictionary, possible better solution is json.loads
. The main limitation is that json dicts requires string keys. Also you can only provide literal data, but that is also the case for literal_eval
.
Cshtml files are the ones used by Razor and as stated as answer for this question, their main advantage is that they can be rendered inside unit tests. The various answers to this other topic will bring a lot of other interesting points.
It may be useful to know that starting from Android 8.0 (API level 26) you can use a custom font in XML.
You can apply a custom font to the entire application in the following way.
Put the font in the folder res/font
.
In res/values/styles.xml
use it in the application theme.
<style name="AppTheme" parent="{whatever you like}">
<item name="android:fontFamily">@font/myfont</item>
</style>
%RANDOM%
gives you a random number between 0 and 32767.
Using an expression like SET /A test=%RANDOM% * 100 / 32768 + 1
, you can change the range to anything you like (here the range is [1ā¦100] instead of [0ā¦32767]).
use this script
$('input[name=q12_3]').is(":checked");
NOTE: AppJS is deprecated and not recommended anymore.
Take a look at NW.js instead.
In my case, the issue was new sites had an implicit deny of all IP addresses unless an explicit allow was created. To fix: Under the site in Features View: Under the IIS Section > IP Address and Domain Restrictions > Edit Feature Settings > Set 'Access for unspecified clients:' to 'Allow'
An established connection was aborted by the software in your host machine
That is a boiler-plate error message, it comes out of Windows. The underlying error code is WSAECONNABORTED. Which really doesn't mean more than "connection was aborted". You have to be a bit careful about the "your host machine" part of the phrase. In the vast majority of Windows application programs, it is indeed the host that the desktop app is connected to that aborted the connection. Usually a server somewhere else.
The roles are reversed however when you implement your own server. Now you need to read the error message as "aborted by the application at the other end of the wire". Which is of course not uncommon when you implement a server, client programs that use your server are not unlikely to abort a connection for whatever reason. It can mean that a fire-wall or a proxy terminated the connection but that's not very likely since they typically would not allow the connection to be established in the first place.
You don't really know why a connection was aborted unless you have insight what is going on at the other end of the wire. That's of course hard to come by. If your server is reachable through the Internet then don't discount the possibility that you are being probed by a port scanner. Or your customers, looking for a game cheat.
As of C++11 you can use:
static constexpr int N = 10;
This theoretically still requires you to define the constant in a .cpp file, but as long as you don't take the address of N
it is very unlikely that any compiler implementation will produce an error ;).
intuitive one-liner
document.write(unescape('%3Cscript src="https://code.jquery.com/jquery-3.1.1.min.js"%3E%3C/script%3Eā))
You can change the src
address.
I referred to ReferenceError: Can't find variable: jQuery
@MrBean - I was in a similar situation where I had to call a 3rd-party web service and pass in the Android device's current timezone offset in the format +/-hh:mm. Here is my solution:
public static String getCurrentTimezoneOffset() {
TimeZone tz = TimeZone.getDefault();
Calendar cal = GregorianCalendar.getInstance(tz);
int offsetInMillis = tz.getOffset(cal.getTimeInMillis());
String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60));
offset = (offsetInMillis >= 0 ? "+" : "-") + offset;
return offset;
}
If you're getting source in Content Use the following method
try
{
var response = restClient.Execute<List<EmpModel>>(restRequest);
var jsonContent = response.Content;
var data = JsonConvert.DeserializeObject<List<EmpModel>>(jsonContent);
foreach (EmpModel item in data)
{
listPassingData?.Add(item);
}
}
catch (Exception ex)
{
Console.WriteLine($"Data get mathod problem {ex} ");
}
This will override console.log function when the url does not contain localhost. You can replace the localhost with your own development settings.
// overriding console.log in production
if(window.location.host.indexOf('localhost:9000') < 0) {
console.log = function(){};
}
#include <algorithm>
#include <string>
std::string str = "Hello World";
std::transform(str.begin(), str.end(),str.begin(), ::toupper);
vs2017 just added in these lines to csproj.user file
<IISExpressAnonymousAuthentication>enabled</IISExpressAnonymousAuthentication>
<IISExpressWindowsAuthentication>enabled</IISExpressWindowsAuthentication>
<IISExpressUseClassicPipelineMode>false</IISExpressUseClassicPipelineMode>
with these lines in Web.config
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" maxRequestLength="1048576" />
<identity impersonate="false" />
<authentication mode="Windows" />
<authorization>
<allow users="yourNTusername" />
<deny users="?" />
</authorization>
And it worked
In case you need to use another profile, especially cross account. you need to add the profile in the config file
[profile profileName]
region = us-east-1
role_arn = arn:aws:iam::XXX:role/XXXX
source_profile = default
and then if you are accessing only a single file
aws s3 cp s3://crossAccountBucket/dir localdir --profile profileName
Obviously you know how this defeats the whole purpose of a SecureString, but I'll restate it anyway.
If you want a one-liner, try this: (.NET 4 and above only)
string password = new System.Net.NetworkCredential(string.Empty, securePassword).Password;
Where securePassword is a SecureString.
ATTENTION! If you only want to remove a file from your previous commit, and keep it on disk, read juzzlin's answer just above.
If this is your last commit and you want to completely delete the file from your local and the remote repository, you can:
git rm <file>
git commit --amend
The amend flag tells git to commit again, but "merge" (not in the sense of merging two branches) this commit with the last commit.
As stated in the comments, using git rm
here is like using the rm
command itself!
You should put all your words into some kind of Collection or List and then call it like this:
var searchFor = new List<string>();
searchFor.Add("pineapple");
searchFor.Add("mango");
bool containsAnySearchString = searchFor.Any(word => compareString.Contains(word));
If you need to make a case or culture independent search you should call it like this:
bool containsAnySearchString =
searchFor.Any(word => compareString.IndexOf
(word, StringComparison.InvariantCultureIgnoreCase >= 0);
I think this question is about web icons. I've tried giving an icon at 512x512, and on the iPhone 4 simulator it looks great (in the preview) however, when added to the home-screen it's badly pixelated.
On the good side, if you use a larger icon on the iPad (still with my 512x512 test) it does seem to come out in better quality on the iPad. Hopefully the iPhone 4 rendering is a bug.
I've opened a bug about this on radar.
EDIT:
I'm currently using a 114x114 icon in hopes that it'll look good on the iPhone 4 when it is released. If the iPhone 4 still has a bug when it comes out, I'm going to optimize the icon for the iPad (crisp and no resize at 72x72), and then let it scale down for old iPhones.
Another option that enforces exact matching (i.e. no partial matching) would be:
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))
End Function
You can read more about the Match method and its arguments at http://msdn.microsoft.com/en-us/library/office/ff835873(v=office.15).aspx
The solution that worked for me with PHP / PDO.
public function createTrainingDatabase($p_iRecordnr){
// Methode: Create an database envirioment for a student by copying the original
// @parameter: $p_iRecordNumber, type:integer, scope:local
// @var: $this->sPdoQuery, type:string, scope:member
// @var: $bSuccess, type:boolean, scope:local
// @var: $aTables, type:array, scope:local
// @var: $iUsernumber, type:integer, scope:local
// @var: $sNewDBName, type:string, scope:local
// @var: $iIndex, type:integer, scope:local
// -- Create first the name of the new database --
$aStudentcard = $this->fetchUsercardByRecordnr($p_iRecordnr);
$iUserNumber = $aStudentcard[0][3];
$sNewDBName = $_SESSION['DB_name']."_".$iUserNumber;
// -- Then create the new database --
$this->sPdoQuery = "CREATE DATABASE `".$sNewDBName."`;";
$this->PdoSqlReturnTrue();
// -- Create an array with the tables you want to be copied --
$aTables = array('1eTablename','2ndTablename','3thTablename');
// -- Populate the database --
for ($iIndex = 0; $iIndex < count($aTables); $iIndex++)
{
// -- Create the table --
$this->sPdoQuery = "CREATE TABLE `".$sNewDBName."`.`".$aTables[$iIndex]."` LIKE `".$_SESSION['DB_name']."`.`".$aTables[$iIndex]."`;";
$bSuccess = $this->PdoSqlReturnTrue();
if(!$bSuccess ){echo("Could not create table: ".$aTables[$iIndex]."<BR>");}
else{echo("Created the table ".$aTables[$iIndex]."<BR>");}
// -- Fill the table --
$this->sPdoQuery = "REPLACE `".$sNewDBName."`.`".$aTables[$iIndex]."` SELECT * FROM `".$_SESSION['DB_name']."`.`".$aTables[$iIndex]."`";
$bSuccess = $this->PdoSqlReturnTrue();
if(!$bSuccess ){echo("Could not fill table: ".$aTables[$iIndex]."<BR>");}
else{echo("Filled table ".$aTables[$index]."<BR>");}
}
}
Here is a great resource from Microsoft which includes a high level features overview for each .NET release since 1.0 up to the present day. It also include information about the associated Visual Studio release and Windows version compatibility.
If I had to guess, I'd say that you're from a Java background. This is C++, and things are passed by value unless you specify otherwise using the &
-operator (note that this operator is also used as the 'address-of' operator, but in a different context). This is all well documented, but I'll re-iterate anyway:
void foo(vector<int> bar); // by value
void foo(vector<int> &bar); // by reference (non-const, so modifiable inside foo)
void foo(vector<int> const &bar); // by const-reference
You can also choose to pass a pointer to a vector (void foo(vector<int> *bar)
), but unless you know what you're doing and you feel that this is really is the way to go, don't do this.
Also, vectors are not the same as arrays! Internally, the vector keeps track of an array of which it handles the memory management for you, but so do many other STL containers. You can't pass a vector to a function expecting a pointer or array or vice versa (you can get access to (pointer to) the underlying array and use this though). Vectors are classes offering a lot of functionality through its member-functions, whereas pointers and arrays are built-in types. Also, vectors are dynamically allocated (which means that the size may be determined and changed at runtime) whereas the C-style arrays are statically allocated (its size is constant and must be known at compile-time), limiting their use.
I suggest you read some more about C++ in general (specifically array decay), and then have a look at the following program which illustrates the difference between arrays and pointers:
void foo1(int *arr) { cout << sizeof(arr) << '\n'; }
void foo2(int arr[]) { cout << sizeof(arr) << '\n'; }
void foo3(int arr[10]) { cout << sizeof(arr) << '\n'; }
void foo4(int (&arr)[10]) { cout << sizeof(arr) << '\n'; }
int main()
{
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
foo1(arr);
foo2(arr);
foo3(arr);
foo4(arr);
}
Here is a minor variation on Aleksandr Petrov's response using ES6
removePeople(e) {
let filteredArray = this.state.people.filter(item => item !== e.target.value)
this.setState({people: filteredArray});
}
You need to do empty_set = set()
to initialize an empty set. {}
is an empty dict
.
This error is caused by:
Y = Dataset.iloc[:,18].values
Indexing is out of bounds here most probably because there are less than 19 columns in your Dataset, so column 18 does not exist. The following code you provided doesn't use Y at all, so you can just comment out this line for now.
This is cleaner and will put in a csv.
Import-Module ActiveDirectory
$Groups = (Get-AdGroup -filter * | Where {$_.name -like "**"} | select name -expandproperty name)
$Table = @()
$Record = [ordered]@{
"Group Name" = ""
"Name" = ""
"Username" = ""
}
Foreach ($Group in $Groups)
{
$Arrayofmembers = Get-ADGroupMember -identity $Group | select name,samaccountname
foreach ($Member in $Arrayofmembers)
{
$Record."Group Name" = $Group
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord
}
}
$Table | export-csv "C:\temp\SecurityGroups.csv" -NoTypeInformation
I'm a new user for Spring. I found a different solution for this. Using reflection and making public necessary fields and assign mock objects.
This is my auth controller and it has some Autowired private properties.
@RestController
public class AuthController {
@Autowired
private UsersDAOInterface usersDao;
@Autowired
private TokensDAOInterface tokensDao;
@RequestMapping(path = "/auth/getToken", method = RequestMethod.POST)
public @ResponseBody Object getToken(@RequestParam String username,
@RequestParam String password) {
User user = usersDao.getLoginUser(username, password);
if (user == null)
return new ErrorResult("Kullaniciadi veya sifre hatali");
Token token = new Token();
token.setTokenId("aergaerg");
token.setUserId(1);
token.setInsertDatetime(new Date());
return token;
}
}
And this is my Junit test for AuthController. I'm making public needed private properties and assign mock objects to them and rock :)
public class AuthControllerTest {
@Test
public void getToken() {
try {
UsersDAO mockUsersDao = mock(UsersDAO.class);
TokensDAO mockTokensDao = mock(TokensDAO.class);
User dummyUser = new User();
dummyUser.setId(10);
dummyUser.setUsername("nixarsoft");
dummyUser.setTopId(0);
when(mockUsersDao.getLoginUser(Matchers.anyString(), Matchers.anyString())) //
.thenReturn(dummyUser);
AuthController ctrl = new AuthController();
Field usersDaoField = ctrl.getClass().getDeclaredField("usersDao");
usersDaoField.setAccessible(true);
usersDaoField.set(ctrl, mockUsersDao);
Field tokensDaoField = ctrl.getClass().getDeclaredField("tokensDao");
tokensDaoField.setAccessible(true);
tokensDaoField.set(ctrl, mockTokensDao);
Token t = (Token) ctrl.getToken("test", "aergaeg");
Assert.assertNotNull(t);
} catch (Exception ex) {
System.out.println(ex);
}
}
}
I don't know advantages and disadvantages for this way but this is working. This technic has a little bit more code but these codes can be seperated by different methods etc. There are more good answers for this question but I want to point to different solution. Sorry for my bad english. Have a good java to everybody :)
I came up with a simple solution.
I have a model.cs class with:
private int _isSuccess;
public int IsSuccess { get { return _isSuccess; } set { _isSuccess = value; } }
I have Window1.xaml.cs file with DataContext set to model.cs. The xaml contains the radiobuttons:
<RadioButton IsChecked="{Binding Path=IsSuccess, Converter={StaticResource radioBoolToIntConverter}, ConverterParameter=1}" Content="one" />
<RadioButton IsChecked="{Binding Path=IsSuccess, Converter={StaticResource radioBoolToIntConverter}, ConverterParameter=2}" Content="two" />
<RadioButton IsChecked="{Binding Path=IsSuccess, Converter={StaticResource radioBoolToIntConverter}, ConverterParameter=3}" Content="three" />
Here is my converter:
public class RadioBoolToIntConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int integer = (int)value;
if (integer==int.Parse(parameter.ToString()))
return true;
else
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return parameter;
}
}
And of course, in Window1's resources:
<Window.Resources>
<local:RadioBoolToIntConverter x:Key="radioBoolToIntConverter" />
</Window.Resources>
Programmers are lazy...er....efficient....I'd do it like so:
<select><?php
$the_key = 1; // or whatever you want
foreach(array(
1 => 'Yes',
2 => 'No',
3 => 'Fine',
) as $key => $val){
?><option value="<?php echo $key; ?>"<?php
if($key==$the_key)echo ' selected="selected"';
?>><?php echo $val; ?></option><?php
}
?></select>
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
The answer is no, but for me I did the following
the script: myExport
#! \bin\bash
export $1
an alias in my .bashrc
alias myExport='source myExport'
Still you source it, but maybe in this way it is more useable and it is interesting for someone else.
I use this kind of wrapping exception:
public class CheckedExceptionWrapper extends RuntimeException {
...
public <T extends Exception> CheckedExceptionWrapper rethrow() throws T {
throw (T) getCause();
}
}
It will require handling these exceptions statically:
void method() throws IOException, ServletException {
try {
list.stream().forEach(object -> {
...
throw new CheckedExceptionWrapper(e);
...
});
} catch (CheckedExceptionWrapper e){
e.<IOException>rethrow();
e.<ServletExcepion>rethrow();
}
}
Though exception will be anyway re-thrown during first rethrow()
call (oh, Java generics...), this way allows to get a strict statical definition of possible exceptions (requires to declare them in throws
). And no instanceof
or something is needed.
Another alternative is to use a lambda:
ent.bind("<Return>", (lambda event: name_of_function()))
Full code:
from tkinter import *
from tkinter.messagebox import showinfo
def reply(name):
showinfo(title="Reply", message = "Hello %s!" % name)
top = Tk()
top.title("Echo")
top.iconbitmap("Iconshock-Folder-Gallery.ico")
Label(top, text="Enter your name:").pack(side=TOP)
ent = Entry(top)
ent.bind("<Return>", (lambda event: reply(ent.get())))
ent.pack(side=TOP)
btn = Button(top,text="Submit", command=(lambda: reply(ent.get())))
btn.pack(side=LEFT)
top.mainloop()
As you can see, creating a lambda function with an unused variable "event" solves the problem.
You could try adding this to your environment variables:
PYTHONHTTPSVERIFY=0
Note that this will disable all HTTPS verification so is a bit of a sledgehammer approach, however if verification isn't required it may be an effective solution.
Use the keyword next
. If you do not want to continue to the next item, use break
.
When next
is used within a block, it causes the block to exit immediately, returning control to the iterator method, which may then begin a new iteration by invoking the block again:
f.each do |line| # Iterate over the lines in file f
next if line[0,1] == "#" # If this line is a comment, go to the next
puts eval(line)
end
When used in a block, break
transfers control out of the block, out of the iterator that invoked the block, and to the first expression following the invocation of the iterator:
f.each do |line| # Iterate over the lines in file f
break if line == "quit\n" # If this break statement is executed...
puts eval(line)
end
puts "Good bye" # ...then control is transferred here
And finally, the usage of return
in a block:
return
always causes the enclosing method to return, regardless of how deeply nested within blocks it is (except in the case of lambdas):
def find(array, target)
array.each_with_index do |element,index|
return index if (element == target) # return from find
end
nil # If we didn't find the element, return nil
end
I just restarted Visual Studio and did IISRESET which solved the problem.
You can use javascript's indexOf function.
var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";
if(str1.indexOf(str2) != -1){
alert(str2 + " found");
}
You can capture the system environment variables with a vbs script, but you need a bat script to actually change the current environment variables, so this is a combined solution.
Create a file named resetvars.vbs
containing this code, and save it on the path:
Set oShell = WScript.CreateObject("WScript.Shell")
filename = oShell.ExpandEnvironmentStrings("%TEMP%\resetvars.bat")
Set objFileSystem = CreateObject("Scripting.fileSystemObject")
Set oFile = objFileSystem.CreateTextFile(filename, TRUE)
set oEnv=oShell.Environment("System")
for each sitem in oEnv
oFile.WriteLine("SET " & sitem)
next
path = oEnv("PATH")
set oEnv=oShell.Environment("User")
for each sitem in oEnv
oFile.WriteLine("SET " & sitem)
next
path = path & ";" & oEnv("PATH")
oFile.WriteLine("SET PATH=" & path)
oFile.Close
create another file name resetvars.bat containing this code, same location:
@echo off
%~dp0resetvars.vbs
call "%TEMP%\resetvars.bat"
When you want to refresh the environment variables, just run resetvars.bat
Apologetics:
The two main problems I had coming up with this solution were
a. I couldn't find a straightforward way to export environment variables from a vbs script back to the command prompt, and
b. the PATH environment variable is a concatenation of the user and the system PATH variables.
I'm not sure what the general rule is for conflicting variables between user and system, so I elected to make user override system, except in the PATH variable which is handled specifically.
I use the weird vbs+bat+temporary bat mechanism to work around the problem of exporting variables from vbs.
Note: this script does not delete variables.
This can probably be improved.
ADDED
If you need to export the environment from one cmd window to another, use this script (let's call it exportvars.vbs
):
Set oShell = WScript.CreateObject("WScript.Shell")
filename = oShell.ExpandEnvironmentStrings("%TEMP%\resetvars.bat")
Set objFileSystem = CreateObject("Scripting.fileSystemObject")
Set oFile = objFileSystem.CreateTextFile(filename, TRUE)
set oEnv=oShell.Environment("Process")
for each sitem in oEnv
oFile.WriteLine("SET " & sitem)
next
oFile.Close
Run exportvars.vbs
in the window you want to export from, then switch to the window you want to export to, and type:
"%TEMP%\resetvars.bat"
The usual error is one tries to put Content-Type: {multipart/form-data}
into the header of the post request. That will fail, it is best to let Postman do it for you. For example:
The solution is to simply not declare width: 100%
.
The default is width: auto
, which for block-level elements (such as div
), will take the "full space" available anyway (different to how width: 100%
does it).
See: http://jsfiddle.net/U7PhY/2/
Just in case it's not already clear from my answer: just don't set a width
on the child div
.
You might instead be interested in box-sizing: border-box
.
Got an re
trick:
In [28]: import re
In [29]: x = "qwertyui"
In [30]: [x for x in re.split(r'(\w{2})', x) if x]
Out[30]: ['qw', 'er', 'ty', 'ui']
Then be a func, it might looks like:
def split(string, split_len):
# Regex: `r'.{1}'` for example works for all characters
regex = r'(.{%s})' % split_len
return [x for x in re.split(regex, string) if x]
String timestamp = "2019-09-18 21.42.05.000705";
String sub1 = timestamp.substring(0, 19).replace('.', ':');
String sub2 = timestamp.substring(19, timestamp.length());
System.out.println("Original String "+ timestamp);
System.out.println("Replaced Value "+ sub1+sub2);
I can't say this is the most bulletproof or portable solution, but it works for my testing scripts:
.output /tmp/temp_drop_tables.sql
select 'drop table ' || name || ';' from sqlite_master where type = 'table';
.output stdout
.read /tmp/temp_drop_tables.sql
.system rm /tmp/temp_drop_tables.sql
This bit of code redirects output to a temporary file, constructs the 'drop table' commands that I want to run (sending the commands to the temp file), sets output back to standard out, then executes the commands from the file, and finally removes the file.
Open the mysql terminal:
el@apollo:~$ mysql -u root -pthepassword yourdb
mysql>
Drop the function if it already exists
mysql> drop function if exists myfunc;
Query OK, 0 rows affected, 1 warning (0.00 sec)
Create the function
mysql> create function hello(id INT)
-> returns CHAR(50)
-> return 'foobar';
Query OK, 0 rows affected (0.01 sec)
Create a simple table to test it out with
mysql> create table yar (id INT);
Query OK, 0 rows affected (0.07 sec)
Insert three values into the table yar
mysql> insert into yar values(5), (7), (9);
Query OK, 3 rows affected (0.04 sec)
Records: 3 Duplicates: 0 Warnings: 0
Select all the values from yar, run our function hello each time:
mysql> select id, hello(5) from yar;
+------+----------+
| id | hello(5) |
+------+----------+
| 5 | foobar |
| 7 | foobar |
| 9 | foobar |
+------+----------+
3 rows in set (0.01 sec)
Verbalize and internalize what just happened:
You created a function called hello which takes one parameter. The parameter is ignored and returns a CHAR(50)
containing the value 'foobar'. You created a table called yar and added three rows to it. The select statement runs the function hello(5)
for each row returned by yar.
From the manual: The SELECT ... INTO OUTFILE
statement is intended primarily to let you very quickly dump a table to a text file on the server machine. If you want to create the resulting file on some client host other than the server host, you cannot use SELECT ... INTO OUTFILE
. In that case, you should instead use a command such as mysql -e "SELECT ..." > file_name
to generate the file on the client host."
http://dev.mysql.com/doc/refman/5.0/en/select.html
An example:
mysql -h my.db.com -u usrname--password=pass db_name -e 'SELECT foo FROM bar' > /tmp/myfile.txt
In Python self
is the conventional name given to the first argument of instance methods of classes, which is always the instance the method was called on:
class A(object):
def f(self):
print self
a = A()
a.f()
Will give you something like
<__main__.A object at 0x02A9ACF0>
Modified erikkallen answer:
$(document).unbind('keydown').bind('keydown', function (event) {
var doPrevent = false, elem;
if (event.keyCode === 8) {
elem = event.srcElement || event.target;
if( $(elem).is(':input') ) {
doPrevent = elem.readOnly || elem.disabled;
} else {
doPrevent = true;
}
}
if (doPrevent) {
event.preventDefault();
return false;
}
});
text.setTextColor(getResource().getColor(R.color.black))
you have create black color in color.xml.
OR
text.setTextColor(Color.parseColor("#000000"))
here type desired hexcode
OR
text.setTextColor(Color.BLACK)
you can use static color fields
If it's GNU diff then you should just be able to point it at the two directories and use the -r option.
Otherwise, try using
for i in $(\ls -d ./dir1/*); do diff ${i} dir2; done
N.B. As pointed out by Dennis in the comments section, you don't actually need to do the command substitution on the ls. I've been doing this for so long that I'm pretty much doing this on autopilot and substituting the command I need to get my list of files for comparison.
Also I forgot to add that I do '\ls' to temporarily disable my alias of ls to GNU ls so that I lose the colour formatting info from the listing returned by GNU ls.
As long as there are no duplicates (and trains tend to only arrive at one station at a time)...
select Train, MAX(Time),
max(Dest) keep (DENSE_RANK LAST ORDER BY Time) max_keep
from TrainTable
GROUP BY Train;
Use
text-align: right
The text-align CSS property describes how inline content like text is aligned in its parent block element. text-align does not control the alignment of block elements itself, only their inline content.
See
<td class='alnright'>text to be aligned to right</td>
<style>
.alnright { text-align: right; }
</style>
It appears that the :include
functionality was changed with Rails 2.1. Rails used to do the join in all cases, but for performance reasons it was changed to use multiple queries in some circumstances. This blog post by Fabio Akita has some good information on the change (see the section entitled "Optimized Eager Loading").
Additionally if you need to restrict the grouping you can use:
db.events.aggregate(
{$match: {province: "ON"}},
{$group: {_id: "$date", number: {$sum: 1}}}
)
Android changed how permissions work with Android 6.0 that's the reason for your errors. You have to actually request and check if the permission was granted by user to use. So permissions in manifest file will only work for api below 21. Check this link for a snippet of how permissions are requested in api23 http://android-developers.blogspot.nl/2015/09/google-play-services-81-and-android-60.html?m=1
Code:-
If (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_RC);
return;
}`
` @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == STORAGE_PERMISSION_RC) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//permission granted start reading
} else {
Toast.makeText(this, "No permission to read external storage.", Toast.LENGTH_SHORT).show();
}
}
}
}
This is the simple only you have to set background color as transparent
ImageButton btn=(ImageButton)findViewById(R.id.ImageButton01);
btn.setBackgroundColor(Color.TRANSPARENT);
Use it after initialization code to get current date (in datepicker format):
$(".ui-datepicker-today").trigger("click");
The -jar
option only works if the JAR file is an executable JAR file, which means it must have a manifest file with a Main-Class
attribute in it.
If it's not an executable JAR, then you'll need to run the program with something like:
java -cp app.jar com.somepackage.SomeClass
where com.somepackage.SomeClass
is the class that contains the main
method to run the program.
You can use html and be a boss with simple things :
<embed src="music.mp3" width="3000" height="200" controls>
To me it happened in DogController
that autowired DogService
that autowired DogRepository
. Dog
class used to have field name
but I changed it to coolName
, but didn't change methods in DogRepository
: Dog findDogByName(String name)
. I change that method to Dog findDogByCoolName(String name)
and now it works.
I would prefer using JConsole for application monitoring, and it does have graphical view. If youāre using JDK 5.0 or above then itās the best. Please refer to this using jconsole page for more details.
I have been primarily using it for GC tuning and finding bottlenecks.
I could not use:
ansible_ssh_common_args='-o StrictHostKeyChecking=no'
in inventory file. It seems ansible does not consider this option in my case (ansible 2.0.1.0 from pip in ubuntu 14.04)
I decided to use:
server ansible_host=192.168.1.1 ansible_ssh_common_args= '-o UserKnownHostsFile=/dev/null'
It helped me.
Also you could set this variable in group instead for each host:
[servers_group:vars]
ansible_ssh_common_args='-o UserKnownHostsFile=/dev/null'
Check the trees.config file which located in config folder... sometimes (I don't know why) this file became to be empty like someone delete the content inside... keep backup up of this file in your local pc then when this error appear - replace the server file with your local file. This is what i do when this error happened.
check the available space on the server. sometimes this is the problem.
Good luck.
I just wanted to contribute this should someone be looking for help with adding separators between the strings, depending on whether a field is NULL or not.
So in the example of creating a one line address from separate fields
Address1, Address2, Address3, City, PostCode
in my case, I have the following Calculated Column which seems to be working as I want it:
case
when [Address1] IS NOT NULL
then ((( [Address1] +
isnull(', '+[Address2],'')) +
isnull(', '+[Address3],'')) +
isnull(', '+[City] ,'')) +
isnull(', '+[PostCode],'')
end
Hope that helps someone!
I think this will happen if you'll use 'async defer' for (the file that contains the filter) while working with angularjs:
<script src="js/filter.js" type="text/javascript" async defer></script>
if you do, just remove 'async defer'.
I made a POC for an Angular application using multiple modules and router-outlets to nest sub apps in a single page app. You can get the source code at: https://github.com/AhmedBahet/ng-sub-apps
Hope this will help
If you don't want to use a watcher, you can do something like this:
<input type='checkbox' ng-init='checkStatus=false' ng-model='checkStatus' ng-click='doIfChecked(checkStatus)'>
The other answers here are correct, but they don't get into how instanceof
actually works, which may be of interest to some language lawyers out there.
Every object in JavaScript has a prototype, accessible through the __proto__
property. Functions also have a prototype
property, which is the initial __proto__
for any objects created by them. When a function is created, it is given a unique object for prototype
. The instanceof
operator uses this uniqueness to give you an answer. Here's what instanceof
might look like if you wrote it as a function.
function instance_of(V, F) {
var O = F.prototype;
V = V.__proto__;
while (true) {
if (V === null)
return false;
if (O === V)
return true;
V = V.__proto__;
}
}
This is basically paraphrasing ECMA-262 edition 5.1 (also known as ES5), section 15.3.5.3.
Note that you can reassign any object to a function's prototype
property, and you can reassign an object's __proto__
property after it is constructed. This will give you some interesting results:
function F() { }
function G() { }
var p = {};
F.prototype = p;
G.prototype = p;
var f = new F();
var g = new G();
f instanceof F; // returns true
f instanceof G; // returns true
g instanceof F; // returns true
g instanceof G; // returns true
F.prototype = {};
f instanceof F; // returns false
g.__proto__ = {};
g instanceof G; // returns false
You can download the free Name Manager addin developed by myself and Jan Karel Pieterse from http://www.decisionmodels.com/downloads.htm This enables many name operations that the Excel 2007 Name manager cannot handle, including changing scope of names.
In VBA:
Sub TestName()
Application.Calculation = xlManual
Names("TestName").Delete
Range("Sheet1!$A$1:$B$2").Name = "Sheet1!TestName"
Application.Calculation = xlAutomatic
End Sub
I have done it something like below for sending my model class from the Second Activity to First Activity. I used LiveData to achieve this, with the help of answers from Rupesh and TheCodeFather.
Second Activity
public static MutableLiveData<AudioListModel> getLiveSong() {
MutableLiveData<AudioListModel> result = new MutableLiveData<>();
result.setValue(liveSong);
return result;
}
"liveSong" is AudioListModel declared globally
Call this method in the First Activity
PlayerActivity.getLiveSong().observe(this, new Observer<AudioListModel>() {
@Override
public void onChanged(AudioListModel audioListModel) {
if (PlayerActivity.mediaPlayer != null && PlayerActivity.mediaPlayer.isPlaying()) {
Log.d("LiveSong--->Changes-->", audioListModel.getSongName());
}
}
});
May this help for new explorers like me.
Client side data validation can be useful for a better user experience: for example, I a user who types wrongly his email address, should not wait til his request is processed by a remote server to learn about the typo he did.
Nevertheless, as an attacker can bypass client side validation (and may even not use the browser at all), server side validation is required, and must be the real gate to protect your backend from nefarious users.
Count()
is an extension method introduced by LINQ while the Count
property is part of the List itself (derived from ICollection
). Internally though, LINQ checks if your IEnumerable
implements ICollection
and if it does it uses the Count
property. So at the end of the day, there's no difference which one you use for a List
.
To prove my point further, here's the code from Reflector for Enumerable.Count()
public static int Count<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
ICollection<TSource> is2 = source as ICollection<TSource>;
if (is2 != null)
{
return is2.Count;
}
int num = 0;
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
num++;
}
}
return num;
}
SELECT *
INTO #Temp
FROM
(SELECT
Received,
Total,
Answer,
(CASE WHEN application LIKE '%STUFF%' THEN 'MORESTUFF' END) AS application
FROM
FirstTable
WHERE
Recieved = 1 AND
application = 'MORESTUFF'
GROUP BY
CASE WHEN application LIKE '%STUFF%' THEN 'MORESTUFF' END) data
WHERE
application LIKE
isNull(
'%MORESTUFF%',
'%')
Beside sys.argv
, also take a look at the argparse module, which helps define options and arguments for scripts.
The argparse module makes it easy to write user-friendly command-line interfaces.
While make itself is available as a standalone executable (gnuwin32.sourceforge.net
package make
), using it in a proper development environment means using msys2.
Git 2.24 (Q4 2019) illustrates that:
See commit 4668931, commit b35304b, commit ab7d854, commit be5d88e, commit 5d65ad1, commit 030a628, commit 61d1d92, commit e4347c9, commit ed712ef, commit 5b8f9e2, commit 41616ef, commit c097b95 (04 Oct 2019), and commit dbcd970 (30 Sep 2019) by Johannes Schindelin (dscho
).
(Merged by Junio C Hamano -- gitster
-- in commit 6d5291b, 15 Oct 2019)
test-tool run-command
: learn to run (parts of) the testsuiteSigned-off-by: Johannes Schindelin
Git for Windows jumps through hoops to provide a development environment that allows to build Git and to run its test suite.
To that end, an entire MSYS2 system, including GNU make and GCC is offered as "the Git for Windows SDK".
It does come at a price: an initial download of said SDK weighs in with several hundreds of megabytes, and the unpacked SDK occupies ~2GB of disk space.A much more native development environment on Windows is Visual Studio. To help contributors use that environment, we already have a Makefile target
vcxproj
that generates a commit with project files (and other generated files), and Git for Windows'vs/master
branch is continuously re-generated using that target.The idea is to allow building Git in Visual Studio, and to run individual tests using a Portable Git.
this works for me, so try it :
Microsoft.Office.Interop.Excel.Range rng =(Microsoft.Office.Interop.Excel.Range)XcelApp.Cells[1, i];
rng.Font.Bold = true;
rng.Interior.Color =System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
rng.BorderAround();
As always, you should question whether you truly need a mutable map.
Immutable maps are trivial to build:
val map = Map(
"mykey" -> "myval",
"myotherkey" -> "otherval"
)
Mutable maps are no different when first being built:
val map = collection.mutable.Map(
"mykey" -> "myval",
"myotherkey" -> "otherval"
)
map += "nextkey" -> "nextval"
In both of these cases, inference will be used to determine the correct type parameters for the Map instance.
You can also hold an immutable map in a var
, the variable will then be updated with a new immutable map instance every time you perform an "update"
var map = Map(
"mykey" -> "myval",
"myotherkey" -> "otherval"
)
map += "nextkey" -> "nextval"
If you don't have any initial values, you can use Map.empty:
val map : Map[String, String] = Map.empty //immutable
val map = Map.empty[String,String] //immutable
val map = collection.mutable.Map.empty[String,String] //mutable
Padding by definition is a positive integer (including 0).
Negative padding would cause the border to collapse into the content (see the box-model page on w3) - this would make the content area smaller than the content, which doesn't make sense.
Let's say you want to repeat '\t' n number of times, you can use;
String.Empty.PadRight(n,'\t')
You can try these lines:
$("#DynamicValueAssignedHere .formdiv form").contents().find("input[name='FirstName']").prevObject[1].value
You should declare Environment Variable for PHP in path, so you could use like this:
C:\Path\to\somewhere>php cli.php
You can do it like this
I've made an answer with some more details here : https://stackoverflow.com/a/11045462/592477
Or you can read it there ==>
When you use loadbalancing it means you have several instances of tomcat and you need to divide loads.
Let the dataframe be named df and the column of interest(i.e. the column in which we are trying to find nulls) is 'b'. Then the following snippet gives the desired index of null in the dataframe:
for i in range(df.shape[0]):
if df['b'].isnull().iloc[i]:
print(i)
You need an event handler which will fire when the button is clicked. Here is a quick way -
var button = new Button();
button.Text = "my button";
this.Controls.Add(button);
button.Click += (sender, args) =>
{
MessageBox.Show("Some stuff");
Close();
};
But it would be better to understand a bit more about buttons, events, etc.
If you use the visual studio UI to create a button and double click the button in design mode, this will create your event and hook it up for you. You can then go to the designer code (the default will be Form1.Designer.cs) where you will find the event:
this.button1.Click += new System.EventHandler(this.button1_Click);
You will also see a LOT of other information setup for the button, such as location, etc. - which will help you create one the way you want and will improve your understanding of creating UI elements. E.g. a default button gives this on my 2012 machine:
this.button1.Location = new System.Drawing.Point(128, 214);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 1;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
As for closing the Form, it is as easy as putting Close(); within your event handler:
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("some text");
Close();
}
If you want to fully copy properties of an object in a different instance, you may want to use this technique:
Serialize it to JSON and then de-serialize it back to Object.
Try the below code this will help you`
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="150dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="@drawable/gallery1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#7ad7d7d7"
android:gravity="center"
android:text="Juneja Art Gallery"
android:textColor="#000000"
android:textSize="15sp"/>
</RelativeLayout>
You can set EditText
's backgroundTint
value to a specific color.
If you set transparent color, underbar should gone.
android:backgroundTint="@color/Transparent"
<color name="Transparent">#00000000</color>
But you can use this in Api v21(Lollipop)
or higher
I'm hoping someone can provide some concrete examples of best use cases for each.
Use Retrofit if you are communicating with a Web service. Use the peer library Picasso if you are downloading images. Use OkHTTP if you need to do HTTP operations that lie outside of Retrofit/Picasso.
Volley roughly competes with Retrofit + Picasso. On the plus side, it is one library. On the minus side, it is one undocumented, an unsupported, "throw the code over the wall and do an I|O presentation on it" library.
EDIT - Volley is now officially supported by Google. Kindly refer Google Developer Guide
From what I've read, seems like OkHTTP is the most robust of the 3
Retrofit uses OkHTTP automatically if available. There is a Gist from Jake Wharton that connects Volley to OkHTTP.
and could handle the requirements of this project (mentioned above).
Probably you will use none of them for "streaming download of audio and video", by the conventional definition of "streaming". Instead, Android's media framework will handle those HTTP requests for you.
That being said, if you are going to attempt to do your own HTTP-based streaming, OkHTTP should handle that scenario; I don't recall how well Volley would handle that scenario. Neither Retrofit nor Picasso are designed for that.
Turns out all I needed to do was wrap the left-hand side of the expression in soft brackets:
<span class="gallery-date">{{(gallery.date | date:'mediumDate') || "Various"}}</span>
Line width in ggplot2
can be changed with argument size=
in geom_line()
.
#sample data
df<-data.frame(x=rnorm(100),y=rnorm(100))
ggplot(df,aes(x=x,y=y))+geom_line(size=2)
I think this should work:
#open file for reading
fn = input("Enter file to open: ")
try:
fh = open(fn,'r')
except:
# if file does not exist, create it
fh = open(fn,'w')
Also, you incorrectly wrote fh = open ( fh, "w")
when the file you wanted open was fn
If you actually care about ordering your paths from shortest path to longest path then it would be far better to use a modified A* or Dijkstra Algorithm. With a slight modification the algorithm will return as many of the possible paths as you want in order of shortest path first. So if what you really want are all possible paths ordered from shortest to longest then this is the way to go.
If you want an A* based implementation capable of returning all paths ordered from the shortest to the longest, the following will accomplish that. It has several advantages. First off it is efficient at sorting from shortest to longest. Also it computes each additional path only when needed, so if you stop early because you dont need every single path you save some processing time. It also reuses data for subsequent paths each time it calculates the next path so it is more efficient. Finally if you find some desired path you can abort early saving some computation time. Overall this should be the most efficient algorithm if you care about sorting by path length.
import java.util.*;
public class AstarSearch {
private final Map<Integer, Set<Neighbor>> adjacency;
private final int destination;
private final NavigableSet<Step> pending = new TreeSet<>();
public AstarSearch(Map<Integer, Set<Neighbor>> adjacency, int source, int destination) {
this.adjacency = adjacency;
this.destination = destination;
this.pending.add(new Step(source, null, 0));
}
public List<Integer> nextShortestPath() {
Step current = this.pending.pollFirst();
while( current != null) {
if( current.getId() == this.destination )
return current.generatePath();
for (Neighbor neighbor : this.adjacency.get(current.id)) {
if(!current.seen(neighbor.getId())) {
final Step nextStep = new Step(neighbor.getId(), current, current.cost + neighbor.cost + predictCost(neighbor.id, this.destination));
this.pending.add(nextStep);
}
}
current = this.pending.pollFirst();
}
return null;
}
protected int predictCost(int source, int destination) {
return 0; //Behaves identical to Dijkstra's algorithm, override to make it A*
}
private static class Step implements Comparable<Step> {
final int id;
final Step parent;
final int cost;
public Step(int id, Step parent, int cost) {
this.id = id;
this.parent = parent;
this.cost = cost;
}
public int getId() {
return id;
}
public Step getParent() {
return parent;
}
public int getCost() {
return cost;
}
public boolean seen(int node) {
if(this.id == node)
return true;
else if(parent == null)
return false;
else
return this.parent.seen(node);
}
public List<Integer> generatePath() {
final List<Integer> path;
if(this.parent != null)
path = this.parent.generatePath();
else
path = new ArrayList<>();
path.add(this.id);
return path;
}
@Override
public int compareTo(Step step) {
if(step == null)
return 1;
if( this.cost != step.cost)
return Integer.compare(this.cost, step.cost);
if( this.id != step.id )
return Integer.compare(this.id, step.id);
if( this.parent != null )
this.parent.compareTo(step.parent);
if(step.parent == null)
return 0;
return -1;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Step step = (Step) o;
return id == step.id &&
cost == step.cost &&
Objects.equals(parent, step.parent);
}
@Override
public int hashCode() {
return Objects.hash(id, parent, cost);
}
}
/*******************************************************
* Everything below here just sets up your adjacency *
* It will just be helpful for you to be able to test *
* It isnt part of the actual A* search algorithm *
********************************************************/
private static class Neighbor {
final int id;
final int cost;
public Neighbor(int id, int cost) {
this.id = id;
this.cost = cost;
}
public int getId() {
return id;
}
public int getCost() {
return cost;
}
}
public static void main(String[] args) {
final Map<Integer, Set<Neighbor>> adjacency = createAdjacency();
final AstarSearch search = new AstarSearch(adjacency, 1, 4);
System.out.println("printing all paths from shortest to longest...");
List<Integer> path = search.nextShortestPath();
while(path != null) {
System.out.println(path);
path = search.nextShortestPath();
}
}
private static Map<Integer, Set<Neighbor>> createAdjacency() {
final Map<Integer, Set<Neighbor>> adjacency = new HashMap<>();
//This sets up the adjacencies. In this case all adjacencies have a cost of 1, but they dont need to.
addAdjacency(adjacency, 1,2,1,5,1); //{1 | 2,5}
addAdjacency(adjacency, 2,1,1,3,1,4,1,5,1); //{2 | 1,3,4,5}
addAdjacency(adjacency, 3,2,1,5,1); //{3 | 2,5}
addAdjacency(adjacency, 4,2,1); //{4 | 2}
addAdjacency(adjacency, 5,1,1,2,1,3,1); //{5 | 1,2,3}
return Collections.unmodifiableMap(adjacency);
}
private static void addAdjacency(Map<Integer, Set<Neighbor>> adjacency, int source, Integer... dests) {
if( dests.length % 2 != 0)
throw new IllegalArgumentException("dests must have an equal number of arguments, each pair is the id and cost for that traversal");
final Set<Neighbor> destinations = new HashSet<>();
for(int i = 0; i < dests.length; i+=2)
destinations.add(new Neighbor(dests[i], dests[i+1]));
adjacency.put(source, Collections.unmodifiableSet(destinations));
}
}
The output from the above code is the following:
[1, 2, 4]
[1, 5, 2, 4]
[1, 5, 3, 2, 4]
Notice that each time you call nextShortestPath()
it generates the next shortest path for you on demand. It only calculates the extra steps needed and doesnt traverse any old paths twice. Moreover if you decide you dont need all the paths and end execution early you've saved yourself considerable computation time. You only compute up to the number of paths you need and no more.
Finally it should be noted that the A* and Dijkstra algorithms do have some minor limitations, though I dont think it would effect you. Namely it will not work right on a graph that has negative weights.
Here is a link to JDoodle where you can run the code yourself in the browser and see it working. You can also change around the graph to show it works on other graphs as well: http://jdoodle.com/a/ukx
You need to fix the spacing and quotes:
export PATH ="/Users/Dz/anaconda/bin:$PATH"
Instead use
export PATH="/Users/Dz/anaconda/bin":$PATH
let formelems = document.querySelectorAll('input,textarea,select');
formelems.forEach((formelem) => {
formelem.required = true;
});
If you wish to make all input, textarea, and select elements required.
You need the full render partial syntax if you are passing locals
<%= render @users, :locals => {:size => 30} %>
Becomes
<%= render :partial => 'users', :collection => @users, :locals => {:size => 30} %>
Or to use the new hash syntax
<%= render partial: 'users', collection: @users, locals: {size: 30} %>
Which I think is much more readable
Try this code:-
var input string
func main() {
fmt.Print("Enter Your Name=")
fmt.Scanf("%s",&input)
fmt.Println("Hello "+input)
}
The only way to remove the dotted line (to my knowledge) is with css hacking using plugin.
Install the User CSS (or User JS & CSS) plugin, which allows adding CSS rules per site.
Once on Google Docs, click the plugins icon, toggle the OFF to ON button, and add the following css code:
.
.kix-page-compact::before{
border-top: none;
}
Should work like a charm.
Excel has no way of gathering that attribute with it's built-in functions. If you're willing to use some VB, all your color-related questions are answered here:
http://www.cpearson.com/excel/colors.aspx
Example form the site:
The SumColor function is a color-based analog of both the SUM and SUMIF function. It allows you to specify separate ranges for the range whose color indexes are to be examined and the range of cells whose values are to be summed. If these two ranges are the same, the function sums the cells whose color matches the specified value. For example, the following formula sums the values in B11:B17 whose fill color is red.
=SUMCOLOR(B11:B17,B11:B17,3,FALSE)
You should be aware of the current conflicts that exists with iOS and RGBA backgrounds.
Summary: public React Native currently exposes the iOS layer shadow properties more-or-less directly, however there are a number of problems with this:
1) Performance when using these properties is poor by default. That's because iOS calculates the shadow by getting the exact pixel mask of the view, including any tranlucent content, and all of its subviews, which is very CPU and GPU-intensive. 2) The iOS shadow properties do not match the syntax or semantics of the CSS box-shadow standard, and are unlikely to be possible to implement on Android. 3) We don't expose the
layer.shadowPath
property, which is crucial to getting good performance out of layer shadows.This diff solves problem number 1) by implementing a default
shadowPath
that matches the view border for views with an opaque background. This improves the performance of shadows by optimizing for the common usage case. I've also reinstated background color propagation for views which have shadow props - this should help ensure that this best-case scenario occurs more often.For views with an explicit transparent background, the shadow will continue to work as it did before (
shadowPath
will be left unset, and the shadow will be derived exactly from the pixels of the view and its subviews). This is the worst-case path for performance, however, so you should avoid it unless absolutely necessary. Support for this may be disabled by default in future, or dropped altogether.For translucent images, it is suggested that you bake the shadow into the image itself, or use another mechanism to pre-generate the shadow. For text shadows, you should use the textShadow properties, which work cross-platform and have much better performance.
Problem number 2) will be solved in a future diff, possibly by renaming the iOS shadowXXX properties to boxShadowXXX, and changing the syntax and semantics to match the CSS standards.
Problem number 3) is now mostly moot, since we generate the shadowPath automatically. In future, we may provide an iOS-specific prop to set the path explicitly if there's a demand for more precise control of the shadow.
Reviewed By: weicool
Commit: https://github.com/facebook/react-native/commit/e4c53c28aea7e067e48f5c8c0100c7cafc031b06
Component:
import { Component, AfterViewInit, ViewChild } from @angular/core;
import { MatPaginator } from @angular/material;
export class ClassName implements AfterViewInit {
@ViewChild(MatPaginator) paginator: MatPaginator;
length = 1000;
pageSize = 10;
pageSizeOptions: number[] = [5, 10, 25, 100];
ngAfterViewInit() {
this.paginator.page.subscribe(
(event) => console.log(event)
);
}
HTML
<mat-paginator
[length]="length"
[pageSize]="pageSize"
[pageSizeOptions]="pageSizeOptions"
[showFirstLastButtons]="true">
</mat-paginator>
On Dreamhost, this worked:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# BEGIN WordPress
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
You can use .present? which comes included with ActiveSupport.
@city = @user.city.present?
# etc ...
You could even write it like this
def show
%w(city state bio contact twitter mail).each do |attr|
instance_variable_set "@#{attr}", @user[attr].present?
end
end
It's worth noting that if you want to test if something is blank, you can use .blank?
(this is the opposite of .present?
)
Also, don't use foo == nil
. Use foo.nil?
instead.
/*
(opener)
*/
(closer)
for example,
<html>
/*<p>Commented P Tag </p>*/
<html>
Here's an example of a function that accepts a callback
const sqk = (x: number, callback: ((_: number) => number)): number => {
// callback will receive a number and expected to return a number
return callback (x * x);
}
// here our callback will receive a number
sqk(5, function(x) {
console.log(x); // 25
return x; // we must return a number here
});
If you don't care about the return values of callbacks (most people don't know how to utilize them in any effective way), you can use void
const sqk = (x: number, callback: ((_: number) => void)): void => {
// callback will receive a number, we don't care what it returns
callback (x * x);
}
// here our callback will receive a number
sqk(5, function(x) {
console.log(x); // 25
// void
});
Note, the signature I used for the callback
parameter ...
const sqk = (x: number, callback: ((_: number) => number)): number
I would say this is a TypeScript deficiency because we are expected to provide a name for the callback parameters. In this case I used _
because it's not usable inside the sqk
function.
However, if you do this
// danger!! don't do this
const sqk = (x: number, callback: ((number) => number)): number
It's valid TypeScript, but it will interpreted as ...
// watch out! typescript will think it means ...
const sqk = (x: number, callback: ((number: any) => number)): number
Ie, TypeScript will think the parameter name is number
and the implied type is any
. This is obviously not what we intended, but alas, that is how TypeScript works.
So don't forget to provide the parameter names when typing your function parameters... stupid as it might seem.
Use the ng-click
directive:
<button my-directive ng-click="alertFn()">Click Me!</button>
// In <script>:
app.directive('myDirective' function() {
return function(scope, element, attrs) {
scope.alertFn = function() { alert('click'); };
};
};
Note that you don't need my-directive
in this example, you just need something to bind alertFn
on the current scope.
Update:
You also want the angular libraries loaded before your <script>
block.
To understand queue method, you have to understand how jQuery does animation. If you write multiple animate method calls one after the other, jQuery creates an 'internal' queue and adds these method calls to it. Then it runs those animate calls one by one.
Consider following code.
function nonStopAnimation()
{
//These multiple animate calls are queued to run one after
//the other by jQuery.
//This is the reason that nonStopAnimation method will return immeidately
//after queuing these calls.
$('#box').animate({ left: '+=500'}, 4000);
$('#box').animate({ top: '+=500'}, 4000);
$('#box').animate({ left: '-=500'}, 4000);
//By calling the same function at the end of last animation, we can
//create non stop animation.
$('#box').animate({ top: '-=500'}, 4000 , nonStopAnimation);
}
The 'queue'/'dequeue' method gives you control over this 'animation queue'.
By default the animation queue is named 'fx'. I have created a sample page here which has various examples which will illustrate how the queue method could be used.
http://jsbin.com/zoluge/1/edit?html,output
Code for above sample page:
$(document).ready(function() {
$('#nonStopAnimation').click(nonStopAnimation);
$('#stopAnimationQueue').click(function() {
//By default all animation for particular 'selector'
//are queued in queue named 'fx'.
//By clearning that queue, you can stop the animation.
$('#box').queue('fx', []);
});
$('#addAnimation').click(function() {
$('#box').queue(function() {
$(this).animate({ height : '-=25'}, 2000);
//De-queue our newly queued function so that queues
//can keep running.
$(this).dequeue();
});
});
$('#stopAnimation').click(function() {
$('#box').stop();
});
setInterval(function() {
$('#currentQueueLength').html(
'Current Animation Queue Length for #box ' +
$('#box').queue('fx').length
);
}, 2000);
});
function nonStopAnimation()
{
//These multiple animate calls are queued to run one after
//the other by jQuery.
$('#box').animate({ left: '+=500'}, 4000);
$('#box').animate({ top: '+=500'}, 4000);
$('#box').animate({ left: '-=500'}, 4000);
$('#box').animate({ top: '-=500'}, 4000, nonStopAnimation);
}
Now you may ask, why should I bother with this queue? Normally, you wont. But if you have a complicated animation sequence which you want to control, then queue/dequeue methods are your friend.
Also see this interesting conversation on jQuery group about creating a complicated animation sequence.
Demo of the animation:
http://www.exfer.net/test/jquery/tabslide/
Let me know if you still have questions.
You can use SQL in Excel. It is only well hidden. See this tutorial:
http://smallbusiness.chron.com/use-sql-statements-ms-excel-41193.html
UPDATED ANSWER:
Old answer, correct method nowadays is to use jQuery's .prop()
. IE, element.prop("selected", true)
OLD ANSWER:
Use this instead:
$("#routetype option[value='quietest']").attr("selected", "selected");
Fiddle'd: http://jsfiddle.net/x3UyB/4/
In VS2019, the project property page, TypeScript Build tab has a setting (dropdown) for "Module System". When I changed that from "ES2015" to CommonJS, then VS2019 IDE stopped complaining that it could find neither axios nor redux-thunk (TS2307).
tsconfig.json:
{
"compilerOptions": {
"allowJs": true,
"baseUrl": "src",
"forceConsistentCasingInFileNames": true,
"jsx": "react",
"lib": [
"es6",
"dom",
"es2015.promise"
],
"module": "esnext",
"moduleResolution": "node",
"noImplicitAny": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noUnusedLocals": true,
"outDir": "build/dist",
"rootDir": "src",
"sourceMap": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"target": "es5",
"skipLibCheck": true,
"strict": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true
},
"exclude": [
"build",
"scripts",
"acceptance-tests",
"webpack",
"jest",
"src/setupTests.ts",
"node_modules",
"obj",
"**/*.spec.ts"
],
"include": [
"src",
"src/**/*.ts",
"@types/**/*.d.ts",
"node_modules/axios",
"node_modules/redux-thunk"
]
}
Just in case you were wondering how to rename columns during aggregation, here's how for
df.groupby('Company Name')['Amount'].agg(MySum='sum', MyCount='count')
Or,
df.groupby('Company Name').agg(MySum=('Amount', 'sum'), MyCount=('Amount', 'count'))
MySum MyCount
Company Name
Vifor Pharma UK Ltd 4207.93 5
The scanner can also use delimiters other than whitespace.
Easy example from Scanner API:
String input = "1 fish 2 fish red fish blue fish";
// \\s* means 0 or more repetitions of any whitespace character
// fish is the pattern to find
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt()); // prints: 1
System.out.println(s.nextInt()); // prints: 2
System.out.println(s.next()); // prints: red
System.out.println(s.next()); // prints: blue
// don't forget to close the scanner!!
s.close();
The point is to understand the regular expressions (regex
) inside the Scanner::useDelimiter
. Find an useDelimiter
tutorial here.
To start with regular expressions here you can find a nice tutorial.
abcā¦ Letters
123ā¦ Digits
\d Any Digit
\D Any Non-digit character
. Any Character
\. Period
[abc] Only a, b, or c
[^abc] Not a, b, nor c
[a-z] Characters a to z
[0-9] Numbers 0 to 9
\w Any Alphanumeric character
\W Any Non-alphanumeric character
{m} m Repetitions
{m,n} m to n Repetitions
* Zero or more repetitions
+ One or more repetitions
? Optional character
\s Any Whitespace
\S Any Non-whitespace character
^ā¦$ Starts and ends
(ā¦) Capture Group
(a(bc)) Capture Sub-group
(.*) Capture all
(ab|cd) Matches ab or cd
No, but you could cast the whole expression rather than the sub-components of that expression. Actually, that probably makes it less readable in this case.
var http = location.protocol;
var slashes = http.concat("//");
var host = slashes.concat(window.location.hostname);
I copied this from one of my apps, so there's prob a few extra attributes, but should give you the idea. This is from the layout that has the progress bar:
<ProgressBar
android:id="@+id/ProgressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:indeterminate="false"
android:maxHeight="10dip"
android:minHeight="10dip"
android:progress="50"
android:progressDrawable="@drawable/greenprogress" />
Then create a new drawable with something similar to the following (In this case greenprogress.xml
):
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
<shape>
<corners android:radius="5dip" />
<gradient
android:angle="270"
android:centerColor="#ff5a5d5a"
android:centerY="0.75"
android:endColor="#ff747674"
android:startColor="#ff9d9e9d" />
</shape>
</item>
<item android:id="@android:id/secondaryProgress">
<clip>
<shape>
<corners android:radius="5dip" />
<gradient
android:angle="270"
android:centerColor="#80ffb600"
android:centerY="0.75"
android:endColor="#a0ffcb00"
android:startColor="#80ffd300" />
</shape>
</clip>
</item>
<item android:id="@android:id/progress">
<clip>
<shape>
<corners android:radius="5dip" />
<gradient
android:angle="270"
android:endColor="#008000"
android:startColor="#33FF33" />
</shape>
</clip>
</item>
</layer-list>
You can change up the colors as needed, this will give you a green progress bar.
Not my fiddle, but http://jsfiddle.net/maxisam/QrCXh/ shows the difference. The key piece is:
scope:{
/* NOTE: Normally I would set my attributes and bindings
to be the same name but I wanted to delineate between
parent and isolated scope. */
isolatedAttributeFoo:'@attributeFoo',
isolatedBindingFoo:'=bindingFoo',
isolatedExpressionFoo:'&'
}
I own a mac too! here is the code that will work:
myButton.setBackground(Color.RED);
myButton.setOpaque(true); //Sets Button Opaque so it works
before doing anything or adding any components set the look and feel so it looks better:
try{
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
}catch(Exception e){
e.printStackTrace();
}
That is Supposed to change the look and feel to the cross platform look and feel, hope i helped! :)
There is no standard way to delay a call to a function other than to use a timer and events.
This sounds like the GUI anti pattern of delaying a call to a method so that you can be sure the form has finished laying out. Not a good idea.
System.currentTimeMillis()
does give you the number of milliseconds since January 1, 1970 00:00:00 UTC. The reason you see local times might be because you convert a Date
instance to a string before using it. You can use DateFormat
s to convert Date
s to String
s in any timezone:
DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
String gmtTime = df.format(new Date());
Actually it seems like Genymotion has an issue with the newer versions of Virtual box, I had the same issue on my Mac but when I downgraded to 4.3.30 it worked like a charm.
[^\u0000-\u007F]+
for any characters which is not included ASCII characters.
For example:
function isNonLatinCharacters(s) {
return /[^\u0000-\u007F]/.test(s);
}
console.log(isNonLatinCharacters("??"));// Japanese
console.log(isNonLatinCharacters("??"));// Chinese
console.log(isNonLatinCharacters("????"));// Persian
console.log(isNonLatinCharacters("???"));// Korean
console.log(isNonLatinCharacters("???????"));// Hindi
console.log(isNonLatinCharacters("???????"));// Hebrew
_x000D_
Here are some perfect references:
Unicode range RegExp generator
As +Volatility and yourself pointed out, sets are unordered. If you need the elements to be in order, just call sorted
on the set:
>>> y = [1, 1, 6, 6, 6, 6, 6, 8, 8]
>>> sorted(set(y))
[1, 6, 8]
I FIGURED IT OUT. SIMPLE, EFFECTIVE NO jQUERY
We're going to to be using a hidden checkbox.
This example includes one "on click - off click 'hover / active' state"
--
To make content itself clickable:
#activate-div{display:none}
.my-div{background-color:#FFF}
#activate-div:checked ~ label
.my-div{background-color:#000}
_x000D_
<input type="checkbox" id="activate-div">
<label for="activate-div">
<div class="my-div">
//MY DIV CONTENT
</div>
</label>
_x000D_
To make button change content:
#activate-div{display:none}
.my-div{background-color:#FFF}
#activate-div:checked +
.my-div{background-color:#000}
_x000D_
<input type="checkbox" id="activate-div">
<div class="my-div">
//MY DIV CONTENT
</div>
<label for="activate-div">
//MY BUTTON STUFF
</label>
_x000D_
Hope it helps!!
One more example of a function to do this: (changing the time and interval formats however you like them according to this for function.date, and this for DateInterval):
(I've also written an alternate form of the below function.)
// Return adjusted time.
function addMinutesToTime( $dateTime, $plusMinutes ) {
$dateTime = DateTime::createFromFormat( 'Y-m-d H:i', $dateTime );
$dateTime->add( new DateInterval( 'PT' . ( (integer) $plusMinutes ) . 'M' ) );
$newTime = $dateTime->format( 'Y-m-d H:i' );
return $newTime;
}
$adjustedTime = addMinutesToTime( '2011-11-17 05:05', 59 );
echo '<h1>Adjusted Time: ' . $adjustedTime . '</h1>' . PHP_EOL . PHP_EOL;
From How do I install a Python package with a .whl file? [sic], How do I install a Python package USING a .whl file ?
For all Windows platforms:
1) Download the .WHL package install file.
2) Make Sure path [C:\Progra~1\Python27\Scripts] is in the system PATH string. This is for using both [pip.exe] and [easy-install.exe].
3) Make sure the latest version of pip.EXE is now installed. At this time of posting:
pip.EXE --version
pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)
4) Run pip.EXE in an Admin command shell.
- Open an Admin privileged command shell.
> easy_install.EXE --upgrade pip
- Check the pip.EXE version:
> pip.EXE --version
pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)
> pip.EXE install --use-wheel --no-index
--find-links="X:\path to wheel file\DownloadedWheelFile.whl"
Be sure to double-quote paths or path\filenames with embedded spaces in them ! Alternatively, use the MSW 'short' paths and filenames.
I have just discovered the round function - it is in Python 2.7, not sure about 2.6. It takes a float and the number of dps as arguments, so round(22.55555, 2) gives the result 22.56.
Override method authenticationManagerBean
in WebSecurityConfigurerAdapter
to expose the AuthenticationManager built using configure(AuthenticationManagerBuilder)
as a Spring bean:
For example:
@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
Using table but without comparing with names
:
numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435)
x <- 67
numbertable <- table(numbers)
numbertable[as.character(x)]
#67
# 2
table
is useful when you are using the counts of different elements several times. If you need only one count, use sum(numbers == x)
As of Ubuntu 20.04 with MySql 8.0 : you can set the password that way:
login to mysql with sudo mysql -u root
change the password:
USE mysql; UPDATE user set authentication_string=NULL where User='root'; FLUSH privileges; ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'My-N7w_And.5ecure-P@s5w0rd'; FLUSH privileges; QUIT
now you should be able to login with mysql -u root -p
(or to phpMyAdmin with username root) and your chosen password.
P,S:
You can also login with user debian-sys-maint
, the password is written in the file /etc/mysql/debian.cnf
I had a similar issues fresh install and same error surprising. Finally I figured out it was a problem with browser cookies...
Try cleaning your browser cookies and see it helps to resolve this issue, before even trying any configuration changes.
Try using XAMPP Control panel "Admin" button instead of usual http://localhost
or http://localhost/phpmyadmin
Try direct link: http://localhost/phpmyadmin/main.php
or http://127.0.0.1/phpmyadmin/main.php
Finally try this: http://localhost/phpmyadmin/index.php?db=phpmyadmin&server=1&target=db_structure.php
Somehow if you have old installation and you upgraded to new version it keeps track of your old settings through cookies.
If this solution helped let me know.
Another possible cause is that the clock of your machine is not synced (e.g. on Raspberry Pi). Check the current date/time using:
$ date
If the date and/or time is incorrect, try to update using:
$ sudo ntpdate -u time.nist.gov
Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly mscorlib
Yes, this technically can go wrong when you execute code on .NET 4.0 instead of .NET 4.5. The attribute was moved from System.Core.dll to mscorlib.dll in .NET 4.5. While that sounds like a rather nasty breaking change in a framework version that is supposed to be 100% compatible, a [TypeForwardedTo] attribute is supposed to make this difference unobservable.
As Murphy would have it, every well intended change like this has at least one failure mode that nobody thought of. This appears to go wrong when ILMerge was used to merge several assemblies into one and that tool was used incorrectly. A good feedback article that describes this breakage is here. It links to a blog post that describes the mistake. It is rather a long article, but if I interpret it correctly then the wrong ILMerge command line option causes this problem:
/targetplatform:"v4,c:\windows\Microsoft.NET\Framework\v4.0.30319"
Which is incorrect. When you install 4.5 on the machine that builds the program then the assemblies in that directory are updated from 4.0 to 4.5 and are no longer suitable to target 4.0. Those assemblies really shouldn't be there anymore but were kept for compat reasons. The proper reference assemblies are the 4.0 reference assemblies, stored elsewhere:
/targetplatform:"v4,C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0"
So possible workarounds are to fall back to 4.0 on the build machine, install .NET 4.5 on the target machine and the real fix, to rebuild the project from the provided source code, fixing the ILMerge command.
Do note that this failure mode isn't exclusive to ILMerge, it is just a very common case. Any other scenario where these 4.5 assemblies are used as reference assemblies in a project that targets 4.0 is liable to fail the same way. Judging from other questions, another common failure mode is in build servers that were setup without using a valid VS license. And overlooking that the multi-targeting packs are a free download.
Using the reference assemblies in the c:\program files (x86) subdirectory is a rock hard requirement. Starting at .NET 4.0, already important to avoid accidentally taking a dependency on a class or method that was added in the 4.01, 4.02 and 4.03 releases. But absolutely essential now that 4.5 is released.
In Ruby 2.1 and higher you can do
{ a: 'a', b: 'b' }.map { |k, str| [k, "%#{str}%"] }.to_h
Works for me too
responsive:true
maintainAspectRatio: false
<div class="row">
<div class="col-xs-12">
<canvas id="mycanvas" width="500" height="300"></canvas>
</div>
</div>
Thank You
In you want to know the data from de selected row, you can try this snippet code:
DataGridView1.SelectedRows.Item(0).Cells(1).Value
Just use percentage widths and fixed table layout:
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</table>
with
table { table-layout: fixed; }
td { width: 33%; }
Fixed table layout is important as otherwise the browser will adjust the widths as it sees fit if the contents don't fit ie the widths are otherwise a suggestion not a rule without fixed table layout.
Obviously, adjust the CSS to fit your circumstances, which usually means applying the styling only to a tables with a given class or possibly with a given ID.
It seems that for Jackson 1.9.12 there is no such possibility by default, because of:
public final static class DateTimeSerializer
extends JodaSerializer<DateTime>
{
public DateTimeSerializer() { super(DateTime.class); }
@Override
public void serialize(DateTime value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonGenerationException
{
if (provider.isEnabled(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS)) {
jgen.writeNumber(value.getMillis());
} else {
jgen.writeString(value.toString());
}
}
@Override
public JsonNode getSchema(SerializerProvider provider, java.lang.reflect.Type typeHint)
{
return createSchemaNode(provider.isEnabled(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS)
? "number" : "string", true);
}
}
This class serializes data using toString() method of Joda DateTime.
Approach proposed by Rusty Kuntz works perfect for my case.
You can use trap
:
try { block A } catch { block B } finally { block C }
translates to:
(
set -Ee
function _catch {
block B
exit 0 # optional; use if you don't want to propagate (rethrow) error to outer shell
}
function _finally {
block C
}
trap _catch ERR
trap _finally EXIT
block A
)
I think, Maatkit utilits helps for you! You can use mk-table-sync. Please see this link: http://www.maatkit.org/doc/mk-table-sync.html
Change:
CONVERT(varchar(3), DATEPART(MONTH, S0.OrderDateTime) AS OrderMonth
To:
CONVERT(varchar(3), DATENAME(MONTH, S0.OrderDateTime)) AS OrderMonth
I think this should work:
#include <time.h>
clock_t start = clock(), diff;
ProcessIntenseFunction();
diff = clock() - start;
int msec = diff * 1000 / CLOCKS_PER_SEC;
printf("Time taken %d seconds %d milliseconds", msec/1000, msec%1000);
You can use Character#toUpperCase()
for this.
char fUpper = Character.toUpperCase(f);
char lUpper = Character.toUpperCase(l);
It has however some limitations since the world is aware of many more characters than can ever fit in 16bit char
range. See also the following excerpt of the javadoc:
Note: This method cannot handle supplementary characters. To support all Unicode characters, including supplementary characters, use the
toUpperCase(int)
method.
Well if you're using angular you could do this too
var newObject = angular.copy(oldObject);
Try the following configuration:
log4j.rootLogger=TRACE, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n
log4j.appender.debugLog=org.apache.log4j.FileAppender
log4j.appender.debugLog.File=logs/debug.log
log4j.appender.debugLog.layout=org.apache.log4j.PatternLayout
log4j.appender.debugLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n
log4j.appender.reportsLog=org.apache.log4j.FileAppender
log4j.appender.reportsLog.File=logs/reports.log
log4j.appender.reportsLog.layout=org.apache.log4j.PatternLayout
log4j.appender.reportsLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n
log4j.category.debugLogger=TRACE, debugLog
log4j.additivity.debugLogger=false
log4j.category.reportsLogger=DEBUG, reportsLog
log4j.additivity.reportsLogger=false
Then configure the loggers in the Java code accordingly:
static final Logger debugLog = Logger.getLogger("debugLogger");
static final Logger resultLog = Logger.getLogger("reportsLogger");
Do you want output to go to stdout
? If not, change the first line of log4j.properties
to:
log4j.rootLogger=OFF
and get rid of the stdout
lines.
Using sed
:
$ echo '1:2:3:4:5' | sed 's/.*://' # => 5
$ echo '' | sed 's/.*://' # => (empty)
$ echo ':' | sed 's/.*://' # => (empty)
$ echo ':b' | sed 's/.*://' # => b
$ echo '::c' | sed 's/.*://' # => c
$ echo 'a' | sed 's/.*://' # => a
$ echo 'a:' | sed 's/.*://' # => (empty)
$ echo 'a:b' | sed 's/.*://' # => b
$ echo 'a::c' | sed 's/.*://' # => c
First create temporary cookie using tempnam() function:
$ckfile = tempnam ("/tmp", "CURLCOOKIE");
Then execute curl init witch saves the cookie as a temporary file:
$ch = curl_init ("http://uri.com/");
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
Or visit a page using the cookie stored in the temporary file:
$ch = curl_init ("http://somedomain.com/cookiepage.php");
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
This will initialize the cookie for the page:
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);
Assuming you actually mean timestamp
because there is no datetime
in Postgres
Cast the timestamp column to a date, that will remove the time part:
select *
from the_table
where the_timestamp_column::date = date '2015-07-15';
This will return all rows from July, 15th.
Note that the above will not use an index on the_timestamp_column
. If performance is critical, you need to either create an index on that expression or use a range condition:
select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
and the_timestamp_column < timestamp '2015-07-16 00:00:00';
You could check if the index is less than the length of the array. This doesn't check for nulls or other odd cases where the index can be assigned a value but hasn't been given one explicitly.
I needed to do this and run a git pull in order to set my password from the command line in order to get this working.
Note this method saves your password in a plain text file on your disk:
git config --global credential.helper store
git pull
Other solutions here: Is there a way to skip password typing when using https:// on GitHub?
I had same problem on Fedora, and found that problem was selinux. to test that it is problem run command: sudo setenforce 0
Otherwise or change in file /etc/sysconfig/selinux
SELINUX=enforcing
to
SELINUX=disabled
or add rules to selinux to allow http access
'-----Implementation of VB6 App object in VBScript-----
Class clsApplication
Property Get Path()
Dim sTmp
If IsObject(Server) Then
'Classic ASP
Path = Server.MapPath("../")
ElseIf IsObject(WScript) Then
'Windows Scripting Host
Path = Left(WScript.ScriptFullName, InStr(WScript.ScriptFullName, WScript.ScriptName) - 2)
ElseIf IsObject(window) Then
'Internet Explorer HTML Application (HTA)
sTmp = Replace( Replace(Unescape(window.location), "file:///", "") ,"/", "\")
Path = Left(sTmp, InstrRev( sTmp , "\") - 1)
End If
End Property
End Class
Dim App : Set App = New clsApplication 'use as App.Path
Yes, it is 128, except for temp tables, whose names can only be up to 116 character long. It is perfectly explained here.
And the verification can be easily made with the following script contained in the blog post before:
DECLARE @i NVARCHAR(800)
SELECT @i = REPLICATE('A', 116)
SELECT @i = 'CREATE TABLE #'+@i+'(i int)'
PRINT @i
EXEC(@i)
You need its pid... use "ps -A" to find it.
Using Double.parseDouble()
without surrounding try/catch
block can cause potential NumberFormatException
had the input double string not conforming to a valid format.
Guava offers a utility method for this which returns null
in case your String can't be parsed.
Double valueDouble = Doubles.tryParse(aPotentiallyCorruptedDoubleString);
In runtime, a malformed String input yields null
assigned to valueDouble
TooTallNate has a simple client side https://github.com/TooTallNate/Java-WebSocket
Just add the java_websocket.jar in the dist folder into your project.
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_10;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONException;
import org.json.JSONObject;
WebSocketClient mWs = new WebSocketClient( new URI( "ws://socket.example.com:1234" ), new Draft_10() )
{
@Override
public void onMessage( String message ) {
JSONObject obj = new JSONObject(message);
String channel = obj.getString("channel");
}
@Override
public void onOpen( ServerHandshake handshake ) {
System.out.println( "opened connection" );
}
@Override
public void onClose( int code, String reason, boolean remote ) {
System.out.println( "closed connection" );
}
@Override
public void onError( Exception ex ) {
ex.printStackTrace();
}
};
//open websocket
mWs.connect();
JSONObject obj = new JSONObject();
obj.put("event", "addChannel");
obj.put("channel", "ok_btccny_ticker");
String message = obj.toString();
//send message
mWs.send(message);
// and to close websocket
mWs.close();
This is now IsEnabled
takePicturebutton.IsEnabled = false; // true
You can use the expandable list view explained in API demos to show groups
To animate the list items motion, you will have to override the getView method and apply translate animation on each list item. The values for animation depend on the position of each list item. This was something which i tried on a simple list view long time back.
To adjust the length of the samples:
set key samplen X
(default is 4)
To adjust the vertical spacing of the samples:
set key spacing X
(default is 1.25)
and (for completeness), to adjust the fontsize:
set key font "<face>,<size>"
(default depends on the terminal)
And of course, all these can be combined into one line:
set key samplen 2 spacing .5 font ",8"
Note that you can also change the position of the key using set key at <position>
or any one of the pre-defined positions (which I'll just defer to help key
at this point)
I would just like to share the recent predicament I encounter with the RecyclerView. I hope that anyone experiencing the same problem will benefit.
My Project Requirement: So I have a RecyclerView that list some clickable items in my Main Activity (Activity-A). When the Item is clicked a new Activity is shown with the Item Details (Activity-B).
I implemented in the Manifest file the that the Activity-A is the parent of Activity-B, that way, I have a back or home button on the ActionBar of the Activity-B
Problem: Every time I pressed the Back or Home button in the Activity-B ActionBar, the Activity-A goes into the full Activity Life Cycle starting from onCreate()
Even though I implemented an onSaveInstanceState() saving the List of the RecyclerView's Adapter, when Activity-A starts it's lifecycle, the saveInstanceState is always null in the onCreate() method.
Further digging in the internet, I came across the same problem but the person noticed that the Back or Home button below the Anroid device (Default Back/Home button), the Activity-A does not goes into the Activity Life-Cycle.
Solution:
I enabled the home or back button on Activity-B
Under onCreate() method add this line supportActionBar?.setDisplayHomeAsUpEnabled(true)
In the overide fun onOptionsItemSelected() method, I checked for the item.ItemId on which item is clicked based on the id. The Id for the back button is
android.R.id.home
Then implement a finish() function call inside the android.R.id.home
This will end the Activity-B and bring Acitivy-A without going through the entire life-cycle.
For my requirement this is the best solution so far.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_show_project)
supportActionBar?.title = projectName
supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when(item?.itemId){
android.R.id.home -> {
finish()
}
}
return super.onOptionsItemSelected(item)
}
According the to Windows Dev Center WIN32_LEAN_AND_MEAN excludes APIs such as Cryptography, DDE, RPC, Shell, and Windows Sockets.
The middle letter of an odd-length word is irrelevant in determining whether the word is a palindrome. Just ignore it.
Hint: all you need is a slight tweak to the following line to make this work for all word lengths:
secondHalf = word[finalWordLength + 1:]
P.S. If you insist on handling the two cases separately, if len(word) % 2: ...
would tell you that the word has an odd number of characters.
They appear to be populated by the tz database time zones found here.
Try chmod u+x foo.sh
instead of chmod +x foo.sh
if you have trouble with the guides above. This worked for me when the other solutions did not.
Use the Array Some Method
var exists = [0,1,2].some(function(count){
return count == 1
});
exists will return true, and you can use this as a variable in your function
if(exists){
console.log('this is true!')
}
When this happened to me it was because my script had DOS line endings, which always messes up the shebang line at the top of the script. I changed it to Unix line endings and it worked.
Or you could use the object tag:
<!--[if IE]>
<object classid="clsid:25336920-03F9-11CF-8FD0-00AA00686F13" data="http://www.google.be">
<p>backup content</p>
</object>
<![endif]-->
<!--[if !IE]> <-->
<object type="text/html" data="http://www.flickr.com" style="width:100%; height:100%">
<p>backup content</p>
</object>
<!--> <![endif]-->
For many types (integer, double, DateTime etc), there is a static Parse method. You can invoke it using reflection:
MethodInfo m = typeof(T).GetMethod("Parse", new Type[] { typeof(string) } );
if (m != null)
{
return m.Invoke(null, new object[] { base.Value });
}
At least with Active Directory, I have been able to search by DistinguishedName by doing an LDAP query in this format (assuming that such a record exists with this distinguishedName):
"(distinguishedName=CN=Dev-India,OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com)"
You can use Environment.Exit(0)
and Application.Exit
.
Environment.Exit()
: terminates this process and gives the underlying operating system the specified exit code.
I know this is a pretty old question but this was my solution that helped with visualizing the table so you can create a class structure. This is also using the HTML Agility Pack
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(@"<html><body><p><table id=""foo""><tr><th>hello</th></tr><tr><td>world</td></tr></table></body></html>");
var table = doc.DocumentNode.SelectSingleNode("//table");
var tableRows = table.SelectNodes("tr");
var columns = tableRows[0].SelectNodes("th/text()");
for (int i = 1; i < tableRows.Count; i++)
{
for (int e = 0; e < columns.Count; e++)
{
var value = tableRows[i].SelectSingleNode($"td[{e + 1}]");
Console.Write(columns[e].InnerText + ":" + value.InnerText);
}
Console.WriteLine();
}
We can use attribute android:background in Button xml like below.
android:background="?android:attr/selectableItemBackground"
Or we can use style
style="?android:attr/borderlessButtonStyle"
for transparent and shadow less background.
I know this question is old now, but after doing a ton of research on various solutions to this problem, I think I may have come up with a better solution.
UPDATE 1: Since posting this answer, I have added all of this code to a simple service that I have posted to GitHub. The repo is located here. Feel free to check it out for more info.
UPDATE 2: This answer is great if all you need is a lightweight solution for pulling in stylesheets for your routes. If you want a more complete solution for managing on-demand stylesheets throughout your application, you may want to checkout Door3's AngularCSS project. It provides much more fine-grained functionality.
In case anyone in the future is interested, here's what I came up with:
1. Create a custom directive for the <head>
element:
app.directive('head', ['$rootScope','$compile',
function($rootScope, $compile){
return {
restrict: 'E',
link: function(scope, elem){
var html = '<link rel="stylesheet" ng-repeat="(routeCtrl, cssUrl) in routeStyles" ng-href="{{cssUrl}}" />';
elem.append($compile(html)(scope));
scope.routeStyles = {};
$rootScope.$on('$routeChangeStart', function (e, next, current) {
if(current && current.$$route && current.$$route.css){
if(!angular.isArray(current.$$route.css)){
current.$$route.css = [current.$$route.css];
}
angular.forEach(current.$$route.css, function(sheet){
delete scope.routeStyles[sheet];
});
}
if(next && next.$$route && next.$$route.css){
if(!angular.isArray(next.$$route.css)){
next.$$route.css = [next.$$route.css];
}
angular.forEach(next.$$route.css, function(sheet){
scope.routeStyles[sheet] = sheet;
});
}
});
}
};
}
]);
This directive does the following things:
$compile
) an html string that creates a set of <link />
tags for every item in the scope.routeStyles
object using ng-repeat
and ng-href
.<link />
elements to the <head>
tag.$rootScope
to listen for '$routeChangeStart'
events. For every '$routeChangeStart'
event, it grabs the "current" $$route
object (the route that the user is about to leave) and removes its partial-specific css file(s) from the <head>
tag. It also grabs the "next" $$route
object (the route that the user is about to go to) and adds any of its partial-specific css file(s) to the <head>
tag.ng-repeat
part of the compiled <link />
tag handles all of the adding and removing of the page-specific stylesheets based on what gets added to or removed from the scope.routeStyles
object.Note: this requires that your ng-app
attribute is on the <html>
element, not on <body>
or anything inside of <html>
.
2. Specify which stylesheets belong to which routes using the $routeProvider
:
app.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/some/route/1', {
templateUrl: 'partials/partial1.html',
controller: 'Partial1Ctrl',
css: 'css/partial1.css'
})
.when('/some/route/2', {
templateUrl: 'partials/partial2.html',
controller: 'Partial2Ctrl'
})
.when('/some/route/3', {
templateUrl: 'partials/partial3.html',
controller: 'Partial3Ctrl',
css: ['css/partial3_1.css','css/partial3_2.css']
})
}]);
This config adds a custom css
property to the object that is used to setup each page's route. That object gets passed to each '$routeChangeStart'
event as .$$route
. So when listening to the '$routeChangeStart'
event, we can grab the css
property that we specified and append/remove those <link />
tags as needed. Note that specifying a css
property on the route is completely optional, as it was omitted from the '/some/route/2'
example. If the route doesn't have a css
property, the <head>
directive will simply do nothing for that route. Note also that you can even have multiple page-specific stylesheets per route, as in the '/some/route/3'
example above, where the css
property is an array of relative paths to the stylesheets needed for that route.
3. You're done Those two things setup everything that was needed and it does it, in my opinion, with the cleanest code possible.
Hope that helps someone else who might be struggling with this issue as much as I was.
No offense, but it's unclever to change class on-the-fly as it forces the CSS interpreter to recalculate the visual presentation of the entire web page.
The reason is that it is nearly impossible for the CSS interpreter to know if any inheritance or cascading could be changed, so the short answer is:
Never ever change className on-the-fly !-)
But usually you'll only need to change a property or two, and that is easily implemented:
function highlight(elm){
elm.style.backgroundColor ="#345";
elm.style.color = "#fff";
}
As MultiPartEntity
is deprecated. So here is the new way to do it! And you only need httpcore.jar(latest)
and httpmime.jar(latest)
download them from Apache site.
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.addTextBody(USER_ID, userId);
entityBuilder.addTextBody(NAME, name);
entityBuilder.addTextBody(TYPE, type);
entityBuilder.addTextBody(COMMENT, comment);
entityBuilder.addTextBody(LATITUDE, String.valueOf(User.Latitude));
entityBuilder.addTextBody(LONGITUDE, String.valueOf(User.Longitude));
if(file != null)
{
entityBuilder.addBinaryBody(IMAGE, file);
}
HttpEntity entity = entityBuilder.build();
post.setEntity(entity);
HttpResponse response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
result = EntityUtils.toString(httpEntity);
Log.v("result", result);
}
catch(Exception e)
{
e.printStackTrace();
}
Default log location (rhel) are
General messages:
/var/log/messages
Authentication messages:
/var/log/secure
Mail events:
/var/log/maillog
Check your /etc/syslog.conf
or /etc/syslog-ng.conf
(it depends on which of syslog facility you have installed)
Example:
$ cat /etc/syslog.conf
# Log anything (except mail) of level info or higher.
# Don't log private authentication messages!
*.info;mail.none;authpriv.none /var/log/messages
# The authpriv file has restricted access.
authpriv.* /var/log/secure
# Log all the mail messages in one place.
mail.* /var/log/maillog
#For a start, use this simplified approach.
*.* /var/log/messages
Any user whose login shell setting in /etc/passwd
is an interactive shell can login. I don't think there's a totally reliable way to tell if a program is an interactive shell; checking whether it's in /etc/shells
is probably as good as you can get.
Other users can also login, but the program they run should not allow them to get much access to the system. And users that aren't allowed to login at all should have /etc/false
as their shell -- this will just log them out immediately.
I think Todd is correct, but I think there's one other thing you should consider. You can reliably get the home directory from the JVM at runtime, and then you can create files objects relative to that location. It's not that much more trouble, and it's something you'll appreciate if you ever move to another computer or operating system.
File homedir = new File(System.getProperty("user.home"));
File fileToRead = new File(homedir, "java/ex.txt");
Connect didn't work for me, The problem was that Genymotion uses its own dk-tools and you need to change it to custom SDK tools.
More info: https://stackoverflow.com/a/26630862/4154438
If you want to know when home is clicked is an AppCompatActivity
then you should try it like this:
First tell Android you want to use your Toolbar
as your ActionBar
:
setSupportActionBar(toolbar);
Then set Home to be displayed via setDisplayShowHomeEnabled
like this:
getSupportActionBar().setDisplayShowHomeEnabled(true);
Finally listen for click events on android.R.id.home
like usual:
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == android.R.id.home) {
Timber.d("Home pressed");
}
return super.onOptionsItemSelected(menuItem);
}
If you want to know when the navigation button is clicked on a Toolbar
in a class other than AppCompatActivity
you can use these methods to set a navigation icon and listen for click events on it. The navigation icon will appear on the left side of your Toolbar
where the the "home" button used to be.
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_nav_back));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("cek", "home selected");
}
});
If you want to know when the hamburger is clicked and when the drawer opens, you're already listening for these events via onDrawerOpened
and onDrawerClosed
so you'll want to see if those callbacks fit your requirements.
You can simply write :
class A(object):
def __init__(self):
print "Initialiser A was called"
class B(A):
def __init__(self):
A.__init__(self)
# A.__init__(self,<parameters>) if you want to call with parameters
print "Initialiser B was called"
class C(B):
def __init__(self):
# A.__init__(self) # if you want to call most super class...
B.__init__(self)
print "Initialiser C was called"
This is an adapter for HashMaps which I implemented for a recent project. Works in a way similart to what @SandyR does, but encapsulates conversion logic so you don't manually convert strings to a wrapper object.
I used Java 8 features but with a few changes, you can adapt it to previous versions. I tested it for most common scenarios, except new Java 8 stream functions.
Basically it wraps a HashMap, directs all functions to it while converting strings to/from a wrapper object. But I had to also adapt KeySet and EntrySet because they forward some functions to the map itself. So I return two new Sets for keys and entries which actually wrap the original keySet() and entrySet().
One note: Java 8 has changed the implementation of putAll method which I could not find an easy way to override. So current implementation may have degraded performance especially if you use putAll() for a large data set.
Please let me know if you find a bug or have suggestions to improve the code.
package webbit.collections;
import java.util.*;
import java.util.function.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public class CaseInsensitiveMapAdapter<T> implements Map<String,T>
{
private Map<CaseInsensitiveMapKey,T> map;
private KeySet keySet;
private EntrySet entrySet;
public CaseInsensitiveMapAdapter()
{
}
public CaseInsensitiveMapAdapter(Map<String, T> map)
{
this.map = getMapImplementation();
this.putAll(map);
}
@Override
public int size()
{
return getMap().size();
}
@Override
public boolean isEmpty()
{
return getMap().isEmpty();
}
@Override
public boolean containsKey(Object key)
{
return getMap().containsKey(lookupKey(key));
}
@Override
public boolean containsValue(Object value)
{
return getMap().containsValue(value);
}
@Override
public T get(Object key)
{
return getMap().get(lookupKey(key));
}
@Override
public T put(String key, T value)
{
return getMap().put(lookupKey(key), value);
}
@Override
public T remove(Object key)
{
return getMap().remove(lookupKey(key));
}
/***
* I completely ignore Java 8 implementation and put one by one.This will be slower.
*/
@Override
public void putAll(Map<? extends String, ? extends T> m)
{
for (String key : m.keySet()) {
getMap().put(lookupKey(key),m.get(key));
}
}
@Override
public void clear()
{
getMap().clear();
}
@Override
public Set<String> keySet()
{
if (keySet == null)
keySet = new KeySet(getMap().keySet());
return keySet;
}
@Override
public Collection<T> values()
{
return getMap().values();
}
@Override
public Set<Entry<String, T>> entrySet()
{
if (entrySet == null)
entrySet = new EntrySet(getMap().entrySet());
return entrySet;
}
@Override
public boolean equals(Object o)
{
return getMap().equals(o);
}
@Override
public int hashCode()
{
return getMap().hashCode();
}
@Override
public T getOrDefault(Object key, T defaultValue)
{
return getMap().getOrDefault(lookupKey(key), defaultValue);
}
@Override
public void forEach(final BiConsumer<? super String, ? super T> action)
{
getMap().forEach(new BiConsumer<CaseInsensitiveMapKey, T>()
{
@Override
public void accept(CaseInsensitiveMapKey lookupKey, T t)
{
action.accept(lookupKey.key,t);
}
});
}
@Override
public void replaceAll(final BiFunction<? super String, ? super T, ? extends T> function)
{
getMap().replaceAll(new BiFunction<CaseInsensitiveMapKey, T, T>()
{
@Override
public T apply(CaseInsensitiveMapKey lookupKey, T t)
{
return function.apply(lookupKey.key,t);
}
});
}
@Override
public T putIfAbsent(String key, T value)
{
return getMap().putIfAbsent(lookupKey(key), value);
}
@Override
public boolean remove(Object key, Object value)
{
return getMap().remove(lookupKey(key), value);
}
@Override
public boolean replace(String key, T oldValue, T newValue)
{
return getMap().replace(lookupKey(key), oldValue, newValue);
}
@Override
public T replace(String key, T value)
{
return getMap().replace(lookupKey(key), value);
}
@Override
public T computeIfAbsent(String key, final Function<? super String, ? extends T> mappingFunction)
{
return getMap().computeIfAbsent(lookupKey(key), new Function<CaseInsensitiveMapKey, T>()
{
@Override
public T apply(CaseInsensitiveMapKey lookupKey)
{
return mappingFunction.apply(lookupKey.key);
}
});
}
@Override
public T computeIfPresent(String key, final BiFunction<? super String, ? super T, ? extends T> remappingFunction)
{
return getMap().computeIfPresent(lookupKey(key), new BiFunction<CaseInsensitiveMapKey, T, T>()
{
@Override
public T apply(CaseInsensitiveMapKey lookupKey, T t)
{
return remappingFunction.apply(lookupKey.key, t);
}
});
}
@Override
public T compute(String key, final BiFunction<? super String, ? super T, ? extends T> remappingFunction)
{
return getMap().compute(lookupKey(key), new BiFunction<CaseInsensitiveMapKey, T, T>()
{
@Override
public T apply(CaseInsensitiveMapKey lookupKey, T t)
{
return remappingFunction.apply(lookupKey.key,t);
}
});
}
@Override
public T merge(String key, T value, BiFunction<? super T, ? super T, ? extends T> remappingFunction)
{
return getMap().merge(lookupKey(key), value, remappingFunction);
}
protected Map<CaseInsensitiveMapKey,T> getMapImplementation() {
return new HashMap<>();
}
private Map<CaseInsensitiveMapKey,T> getMap() {
if (map == null)
map = getMapImplementation();
return map;
}
private CaseInsensitiveMapKey lookupKey(Object key)
{
return new CaseInsensitiveMapKey((String)key);
}
public class CaseInsensitiveMapKey {
private String key;
private String lookupKey;
public CaseInsensitiveMapKey(String key)
{
this.key = key;
this.lookupKey = key.toUpperCase();
}
@Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CaseInsensitiveMapKey that = (CaseInsensitiveMapKey) o;
return lookupKey.equals(that.lookupKey);
}
@Override
public int hashCode()
{
return lookupKey.hashCode();
}
}
private class KeySet implements Set<String> {
private Set<CaseInsensitiveMapKey> wrapped;
public KeySet(Set<CaseInsensitiveMapKey> wrapped)
{
this.wrapped = wrapped;
}
private List<String> keyList() {
return stream().collect(Collectors.toList());
}
private Collection<CaseInsensitiveMapKey> mapCollection(Collection<?> c) {
return c.stream().map(it -> lookupKey(it)).collect(Collectors.toList());
}
@Override
public int size()
{
return wrapped.size();
}
@Override
public boolean isEmpty()
{
return wrapped.isEmpty();
}
@Override
public boolean contains(Object o)
{
return wrapped.contains(lookupKey(o));
}
@Override
public Iterator<String> iterator()
{
return keyList().iterator();
}
@Override
public Object[] toArray()
{
return keyList().toArray();
}
@Override
public <T> T[] toArray(T[] a)
{
return keyList().toArray(a);
}
@Override
public boolean add(String s)
{
return wrapped.add(lookupKey(s));
}
@Override
public boolean remove(Object o)
{
return wrapped.remove(lookupKey(o));
}
@Override
public boolean containsAll(Collection<?> c)
{
return keyList().containsAll(c);
}
@Override
public boolean addAll(Collection<? extends String> c)
{
return wrapped.addAll(mapCollection(c));
}
@Override
public boolean retainAll(Collection<?> c)
{
return wrapped.retainAll(mapCollection(c));
}
@Override
public boolean removeAll(Collection<?> c)
{
return wrapped.removeAll(mapCollection(c));
}
@Override
public void clear()
{
wrapped.clear();
}
@Override
public boolean equals(Object o)
{
return wrapped.equals(lookupKey(o));
}
@Override
public int hashCode()
{
return wrapped.hashCode();
}
@Override
public Spliterator<String> spliterator()
{
return keyList().spliterator();
}
@Override
public boolean removeIf(Predicate<? super String> filter)
{
return wrapped.removeIf(new Predicate<CaseInsensitiveMapKey>()
{
@Override
public boolean test(CaseInsensitiveMapKey lookupKey)
{
return filter.test(lookupKey.key);
}
});
}
@Override
public Stream<String> stream()
{
return wrapped.stream().map(it -> it.key);
}
@Override
public Stream<String> parallelStream()
{
return wrapped.stream().map(it -> it.key).parallel();
}
@Override
public void forEach(Consumer<? super String> action)
{
wrapped.forEach(new Consumer<CaseInsensitiveMapKey>()
{
@Override
public void accept(CaseInsensitiveMapKey lookupKey)
{
action.accept(lookupKey.key);
}
});
}
}
private class EntrySet implements Set<Map.Entry<String,T>> {
private Set<Entry<CaseInsensitiveMapKey,T>> wrapped;
public EntrySet(Set<Entry<CaseInsensitiveMapKey,T>> wrapped)
{
this.wrapped = wrapped;
}
private List<Map.Entry<String,T>> keyList() {
return stream().collect(Collectors.toList());
}
private Collection<Entry<CaseInsensitiveMapKey,T>> mapCollection(Collection<?> c) {
return c.stream().map(it -> new CaseInsensitiveEntryAdapter((Entry<String,T>)it)).collect(Collectors.toList());
}
@Override
public int size()
{
return wrapped.size();
}
@Override
public boolean isEmpty()
{
return wrapped.isEmpty();
}
@Override
public boolean contains(Object o)
{
return wrapped.contains(lookupKey(o));
}
@Override
public Iterator<Map.Entry<String,T>> iterator()
{
return keyList().iterator();
}
@Override
public Object[] toArray()
{
return keyList().toArray();
}
@Override
public <T> T[] toArray(T[] a)
{
return keyList().toArray(a);
}
@Override
public boolean add(Entry<String,T> s)
{
return wrapped.add(null );
}
@Override
public boolean remove(Object o)
{
return wrapped.remove(lookupKey(o));
}
@Override
public boolean containsAll(Collection<?> c)
{
return keyList().containsAll(c);
}
@Override
public boolean addAll(Collection<? extends Entry<String,T>> c)
{
return wrapped.addAll(mapCollection(c));
}
@Override
public boolean retainAll(Collection<?> c)
{
return wrapped.retainAll(mapCollection(c));
}
@Override
public boolean removeAll(Collection<?> c)
{
return wrapped.removeAll(mapCollection(c));
}
@Override
public void clear()
{
wrapped.clear();
}
@Override
public boolean equals(Object o)
{
return wrapped.equals(lookupKey(o));
}
@Override
public int hashCode()
{
return wrapped.hashCode();
}
@Override
public Spliterator<Entry<String,T>> spliterator()
{
return keyList().spliterator();
}
@Override
public boolean removeIf(Predicate<? super Entry<String, T>> filter)
{
return wrapped.removeIf(new Predicate<Entry<CaseInsensitiveMapKey, T>>()
{
@Override
public boolean test(Entry<CaseInsensitiveMapKey, T> entry)
{
return filter.test(new FromCaseInsensitiveEntryAdapter(entry));
}
});
}
@Override
public Stream<Entry<String,T>> stream()
{
return wrapped.stream().map(it -> new Entry<String, T>()
{
@Override
public String getKey()
{
return it.getKey().key;
}
@Override
public T getValue()
{
return it.getValue();
}
@Override
public T setValue(T value)
{
return it.setValue(value);
}
});
}
@Override
public Stream<Map.Entry<String,T>> parallelStream()
{
return StreamSupport.stream(spliterator(), true);
}
@Override
public void forEach(Consumer<? super Entry<String, T>> action)
{
wrapped.forEach(new Consumer<Entry<CaseInsensitiveMapKey, T>>()
{
@Override
public void accept(Entry<CaseInsensitiveMapKey, T> entry)
{
action.accept(new FromCaseInsensitiveEntryAdapter(entry));
}
});
}
}
private class EntryAdapter implements Map.Entry<String,T> {
private Entry<String,T> wrapped;
public EntryAdapter(Entry<String, T> wrapped)
{
this.wrapped = wrapped;
}
@Override
public String getKey()
{
return wrapped.getKey();
}
@Override
public T getValue()
{
return wrapped.getValue();
}
@Override
public T setValue(T value)
{
return wrapped.setValue(value);
}
@Override
public boolean equals(Object o)
{
return wrapped.equals(o);
}
@Override
public int hashCode()
{
return wrapped.hashCode();
}
}
private class CaseInsensitiveEntryAdapter implements Map.Entry<CaseInsensitiveMapKey,T> {
private Entry<String,T> wrapped;
public CaseInsensitiveEntryAdapter(Entry<String, T> wrapped)
{
this.wrapped = wrapped;
}
@Override
public CaseInsensitiveMapKey getKey()
{
return lookupKey(wrapped.getKey());
}
@Override
public T getValue()
{
return wrapped.getValue();
}
@Override
public T setValue(T value)
{
return wrapped.setValue(value);
}
}
private class FromCaseInsensitiveEntryAdapter implements Map.Entry<String,T> {
private Entry<CaseInsensitiveMapKey,T> wrapped;
public FromCaseInsensitiveEntryAdapter(Entry<CaseInsensitiveMapKey, T> wrapped)
{
this.wrapped = wrapped;
}
@Override
public String getKey()
{
return wrapped.getKey().key;
}
@Override
public T getValue()
{
return wrapped.getValue();
}
@Override
public T setValue(T value)
{
return wrapped.setValue(value);
}
}
}