If you have an image imported as a resource in your project there is also this:
picPreview.Image = Properties.Resources.ImageName;
Where picPreview is the name of the picture box and ImageName is the name of the file you want to display.
*Resources are located by going to: Project --> Properties --> Resources
yourPictureBox.ImageLocation = "http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG"
You can do this using the ResourceManager
:
public bool info(string channel)
{
object o = Properties.Resources.ResourceManager.GetObject(channel);
if (o is Image)
{
channelPic.Image = o as Image;
return true;
}
return false;
}
Setting "Copy to Output Directory" to "Copy always" or "Copy if newer" may help for you.
Your PicPath is a relative path that is converted into an absolute path at some time while loading the image.
Most probably you will see that there are no images on the specified location if you use Path.GetFullPath(PicPath)
in Debug.
You can try the following:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog fDialog = new OpenFileDialog();
fDialog.Title = "Select file to be upload";
fDialog.Filter = "All Files|*.*";
// fDialog.Filter = "PDF Files|*.pdf";
if (fDialog.ShowDialog() == DialogResult.OK)
{
textBox1.Text = fDialog.FileName.ToString();
}
}
private void ClearBtn_Click(object sender, EventArgs e)
{
Studentpicture.Image = null;
}
Use the following lines of codes and you will find the solution...
pictureBox1.ImageLocation = @"C:\Users\Desktop\mypicture.jpg";
pictureBox1.SizeMode =PictureBoxSizeMode.StretchImage;
I've had a similar problem like this. You can not make Transparent picturebox easily such as picture that shown at top of this page, because .NET Framework and VS .NET objects are created by INHERITANCE! (Use Parent Property).
I solved this problem by RectangleShape
and with the below code I removed background,
if difference between PictureBox
and RectangleShape
is not important and doesn't matter, you can use RectangleShape
easily.
private void CreateBox(int X, int Y, int ObjectType)
{
ShapeContainer canvas = new ShapeContainer();
RectangleShape box = new RectangleShape();
box.Parent = canvas;
box.Size = new System.Drawing.Size(100, 90);
box.Location = new System.Drawing.Point(X, Y);
box.Name = "Box" + ObjectType.ToString();
box.BackColor = Color.Transparent;
box.BorderColor = Color.Transparent;
box.BackgroundImage = img.Images[ObjectType];// Load from imageBox Or any resource
box.BackgroundImageLayout = ImageLayout.Stretch;
box.BorderWidth = 0;
canvas.Controls.Add(box); // For feature use
}
You can use a ResourceManager to load the image.
See the following link: http://www.java2s.com/Code/CSharp/Development-Class/Saveandloadimagefromresourcefile.htm
As of this date, the correct way according to the dynamic routing docs is:
this.$route.params.yourProperty
instead of
this.$route.query.yourProperty
The problem is caused by using the style="display:none"
, you should hide the alert with Javascript or at least when showing it, remove the style attribute.
If you don't use prioritized tasks, this is actually pretty simple if you're using Redis. To get the task counts:
redis-cli -h HOST -p PORT -n DATABASE_NUMBER llen QUEUE_NAME
But, prioritized tasks use a different key in redis, so the full picture is slightly more complicated. The full picture is that you need to query redis for every priority of task. In python (and from the Flower project), this looks like:
PRIORITY_SEP = '\x06\x16'
DEFAULT_PRIORITY_STEPS = [0, 3, 6, 9]
def make_queue_name_for_pri(queue, pri):
"""Make a queue name for redis
Celery uses PRIORITY_SEP to separate different priorities of tasks into
different queues in Redis. Each queue-priority combination becomes a key in
redis with names like:
- batch1\x06\x163 <-- P3 queue named batch1
There's more information about this in Github, but it doesn't look like it
will change any time soon:
- https://github.com/celery/kombu/issues/422
In that ticket the code below, from the Flower project, is referenced:
- https://github.com/mher/flower/blob/master/flower/utils/broker.py#L135
:param queue: The name of the queue to make a name for.
:param pri: The priority to make a name with.
:return: A name for the queue-priority pair.
"""
if pri not in DEFAULT_PRIORITY_STEPS:
raise ValueError('Priority not in priority steps')
return '{0}{1}{2}'.format(*((queue, PRIORITY_SEP, pri) if pri else
(queue, '', '')))
def get_queue_length(queue_name='celery'):
"""Get the number of tasks in a celery queue.
:param queue_name: The name of the queue you want to inspect.
:return: the number of items in the queue.
"""
priority_names = [make_queue_name_for_pri(queue_name, pri) for pri in
DEFAULT_PRIORITY_STEPS]
r = redis.StrictRedis(
host=settings.REDIS_HOST,
port=settings.REDIS_PORT,
db=settings.REDIS_DATABASES['CELERY'],
)
return sum([r.llen(x) for x in priority_names])
If you want to get an actual task, you can use something like:
redis-cli -h HOST -p PORT -n DATABASE_NUMBER lrange QUEUE_NAME 0 -1
From there you'll have to deserialize the returned list. In my case I was able to accomplish this with something like:
r = redis.StrictRedis(
host=settings.REDIS_HOST,
port=settings.REDIS_PORT,
db=settings.REDIS_DATABASES['CELERY'],
)
l = r.lrange('celery', 0, -1)
pickle.loads(base64.decodestring(json.loads(l[0])['body']))
Just be warned that deserialization can take a moment, and you'll need to adjust the commands above to work with various priorities.
I set the opacity to 0. This made it disappear but still function when you click on it.
We can use any one of these in application.properties file:
spring.jpa.show-sql=true
example :
//Hibernate: select country0_.id as id1_0_, country0_.name as name2_0_ from country country0_
or
logging.level.org.hibernate.SQL=debug
example :
2018-11-23 12:28:02.990 DEBUG 12972 --- [nio-8086-exec-2] org.hibernate.SQL : select country0_.id as id1_0_, country0_.name as name2_0_ from country country0_
Java <= 6.x just allows you to catch one exception for each catch block:
try {
} catch (ExceptionType name) {
} catch (ExceptionType name) {
}
Documentation:
Each catch block is an exception handler and handles the type of exception indicated by its argument. The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class.
For Java 7 you can have multiple Exception caught on one catch block:
catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}
Documentation:
In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.
Reference: http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
The main difference between name()
and toString()
is that name()
is a final
method, so it cannot be overridden. The toString()
method returns the same value that name()
does by default, but toString()
can be overridden by subclasses of Enum.
Therefore, if you need the name of the field itself, use name()
. If you need a string representation of the value of the field, use toString()
.
For instance:
public enum WeekDay {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY;
public String toString() {
return name().charAt(0) + name().substring(1).toLowerCase();
}
}
In this example,
WeekDay.MONDAY.name()
returns "MONDAY", and
WeekDay.MONDAY.toString()
returns "Monday".
WeekDay.valueOf(WeekDay.MONDAY.name())
returns WeekDay.MONDAY
, but WeekDay.valueOf(WeekDay.MONDAY.toString())
throws an IllegalArgumentException
.
There's a much simpler decision.
@app.route('/x')
def x():
return render_template('test.html', foo=y)
def y(text):
return text
Then, in test.html:
{{ foo('hi') }}
There is another way to measure the text bounds precisely, first you should get the path for the current Paint and text. In your case it should be like this:
p.getTextPath(someText, 0, someText.length(), 0.0f, 0.0f, mPath);
After that you can call:
mPath.computeBounds(mBoundsPath, true);
In my code it always returns correct and expected values. But, not sure if it works faster than your approach.
I also had the same problem.The reason for this problem is as Kurtis's descriptions about GNUTLS.
If you have the same reason and your system is Ubuntu, you can solve this problem by installing the latest version of git from ppa:git-core/ppa
.The commands are as below.
sudo add-apt-repository ppa:git-core/ppa
sudo apt-get update
sudo apt-get git
You must use $lastId = $this->db->insert_id();
That's probably a requireJS module definition
Check here for more details
RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.
I think you want to know the total entries count in a table! For that use this code..
SELECT count( * ) as Total_Entries FROM tbl_ifo;
I don't suggest you to use syntax like you did. AngularJs lets you to have different functionalities as you want (run
, config
, service
, factory
, etc..), which are more professional.In this function you don't even have to inject that by yourself like
MainCtrl.$inject = ['$scope', '$rootScope', '$location', 'socket', ...];
you can use it, as you know.
a variable declared with or without the var keyword got attached to the global object. This is the basis for creating global variables in Node by declaring variables without the var keyword. While variables declared with the var keyword remain local to a module.
see this article for further understanding - https://www.hacksparrow.com/global-variables-in-node-js.html
Simple Code
create or replace function get_token(text_is varchar2, token_in number, delim_is varchar2 := ';') return varchar2 is text_ls varchar2(2000); spos_ln number; epos _ln number; begin text_ls := delim_is || text_is || rpad(delim_is, token_in, delim_is); spos_ln := instr(text_ls, delim_is, 1, token_in); epos_ln := instr(text_ls, delim_is, 1, token_in+1); return substr(text_ls, spos_ln+1, epos_ln-spos_ln-1); end get_token;
I've made a gist with THE perfect method to manage fragment replacement and lifecycle.
It only replace the current fragment by a new one, if it's not the same and if it's not in backstack (in this case it will pop it).
It contain several option as if you want the fragment to be saved in backstack.
Using this and a single Activity, you may want to add this to your activity:
@Override
public void onBackPressed() {
int fragments = getSupportFragmentManager().getBackStackEntryCount();
if (fragments == 1) {
finish();
return;
}
super.onBackPressed();
}
mongoimport --jsonArray -d DatabaseN -c collectionName /filePath/filename.json
iPhone
KeyboardSizes:
2.6S,6,7,8:(375 × 667) : keyboardSize = (0.0, 407.0, 375.0, 260.
3.6+,6S+, 7+ , 8+ : (414 × 736) keyboardSize = (0.0, 465.0, 414.0, 271.0)
4.XS, X :(375 X 812) keyboardSize = (0.0, 477.0, 375.0, 335.0)
5.XR,XSMAX((414 x 896) keyboardSize = (0.0, 550.0, 414.0, 346.0)
I know this thread is old... but in "modern times".. there is a far superior "include strategy" via clang's @import
modules - that is oft-overlooked..
Modules improve access to the API of software libraries by replacing the textual preprocessor inclusion model with a more robust, more efficient semantic model. From the user’s perspective, the code looks only slightly different, because one uses an import declaration rather than a #include preprocessor directive:
@import Darwin; // Like including all of /usr/include. @see /usr/include/module.map
or
@import Foundation; // Like #import <Foundation/Foundation.h>
@import ObjectiveC; // Like #import <objc/runtime.h>
However, this module import behaves quite differently from the corresponding #include: when the compiler sees the module import above, it loads a binary representation of the module and makes its API available to the application directly. Preprocessor definitions that precede the import declaration have no impact on the API provided... because the module itself was compiled as a separate, standalone module. Additionally, any linker flags required to use the module will automatically be provided when the module is imported. This semantic import model addresses many of the problems of the preprocessor inclusion model.
To enable modules, pass the command-line flag -fmodules
aka CLANG_ENABLE_MODULES
in Xcode
- at compile time. As mentioned above.. this strategy obviates ANY and ALL LDFLAGS
. As in, you can REMOVE any "OTHER_LDFLAGS" settings, as well as any "Linking" phases..
I find compile / launch times to "feel" much snappier (or possibly, there's just less of a lag while "linking"?).. and also, provides a great opportunity to purge the now extraneous Project-Prefix.pch file, and corresponding build settings, GCC_INCREASE_PRECOMPILED_HEADER_SHARING
, GCC_PRECOMPILE_PREFIX_HEADER
, and GCC_PREFIX_HEADER
, etc.
Also, while not well-documented… You can create module.map
s for your own frameworks and include them in the same convenient fashion. You can take a look at my ObjC-Clang-Modules github repo for some examples of how to implement such miracles.
Use a for
loop instead of .forEach()
var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false
for(var call of myObj) {
console.log(call)
var a = call['a'], b = call['b']
if(a == null || b == null) {
result = false
break
}
}
A solution very simple, but you have to know the index of the original position and the index of the new position:
list1[index1],list1[index2]=list1[index2],list1[index1]
Pat, the json structure looks very familiar to a problem i described here - The answer for me was to treat the json representation as a Dictionary<TKey, TValue>, even though there was only 1 entry.
If I am correct your key is of type string and the value of a List<T> where T represents the class 'TheUser'
HTH
PS - if you want better serialisation perf check out using Silverlight Serializer, you'll need to build a WP7 version, Shameless plug - I wrote a blog post about this
Please use Homebrew Formulae page to see the list of installable packages. https://formulae.brew.sh/formula/
To install any package => command to use is :
brew install node
I think there are three key items you need to understand regarding project structure: Targets, projects, and workspaces. Targets specify in detail how a product/binary (i.e., an application or library) is built. They include build settings, such as compiler and linker flags, and they define which files (source code and resources) actually belong to a product. When you build/run, you always select one specific target.
It is likely that you have a few targets that share code and resources. These different targets can be slightly different versions of an app (iPad/iPhone, different brandings,…) or test cases that naturally need to access the same source files as the app. All these related targets can be grouped in a project. While the project contains the files from all its targets, each target picks its own subset of relevant files. The same goes for build settings: You can define default project-wide settings in the project, but if one of your targets needs different settings, you can always override them there:
Shared project settings that all targets inherit, unless they override it
Concrete target settings: PSE iPhone overrides the project’s Base SDK
setting
In Xcode, you always open projects (or workspaces, but not targets), and all the targets it contains can be built/run, but there’s no way/definition of building a project, so every project needs at least one target in order to be more than just a collection of files and settings.
Select one of the project’s targets to run
In a lot of cases, projects are all you need. If you have a dependency that you build from source, you can embed it as a subproject. Subprojects can be opened separately or within their super project.
demoLib is a subproject
If you add one of the subproject’s targets to the super project’s dependencies, the subproject will be automatically built unless it has remained unchanged. The advantage here is that you can edit files from both your project and your dependencies in the same Xcode window, and when you build/run, you can select from the project’s and its subprojects’ targets:
If, however, your library (the subproject) is used by a variety of other projects (or their targets, to be precise), it makes sense to put it on the same hierarchy level – that’s what workspaces are for. Workspaces contain and manage projects, and all the projects it includes directly (i.e., not their subprojects) are on the same level and their targets can depend on each other (projects’ targets can depend on subprojects’ targets, but not vice versa).
Workspace structure
In this example, both apps (AnotherApplication / ProjectStructureExample) can reference the demoLib project’s targets. This would also be possible by including the demoLib project in both other projects as a subproject (which is a reference only, so no duplication necessary), but if you have lots of cross-dependencies, workspaces make more sense. If you open a workspace, you can choose from all projects’ targets when building/running.
You can still open your project files separately, but it is likely their targets won’t build because Xcode cannot resolve the dependencies unless you open the workspace file. Workspaces give you the same benefit as subprojects: Once a dependency changes, Xcode will rebuild it to make sure it’s up-to-date (although I have had some issues with that, it doesn’t seem to work reliably).
Your questions in a nutshell:
1) Projects contain files (code/resouces), settings, and targets that build products from those files and settings. Workspaces contain projects which can reference each other.
2) Both are responsible for structuring your overall project, but on different levels.
3) I think projects are sufficient in most cases. Don’t use workspaces unless there’s a specific reason. Plus, you can always embed your project in a workspace later.
4) I think that’s what the above text is for…
There’s one remark for 3): CocoaPods, which automatically handles 3rd party libraries for you, uses workspaces. Therefore, you have to use them, too, when you use CocoaPods
(which a lot of people do).
Time 30 minutes later
$newTime = date("Y-m-d H:i:s",strtotime(date("Y-m-d H:i:s")." +30 minutes"))
If anyone has similar issue of having a phone with a cracked screen and has a need to access adb:
If you forgot to enable developers mode and your adb isn't running, then do the following:
adb devices
you should see the device in the list.If so, type:
adb shell mount /system
abd shell
echo "persist.service.adb.enable=1" >> default.prop
echo "persist.service.debuggable=1" >> default.prop
echo "persist.sys.usb.config=mtp,adb" >> default.prop
echo "persist.service.adb.enable=1" >> /system/build.prop
echo "persist.service.debuggable=1" >> /system/build.prop
echo "persist.sys.usb.config=mtp,adb" >> /system/build.prop
Now if you are going to reboot into your phone android will tell you "oh your adb is working but please tap on this OK button, so we can trust your PC". And obviously if we can't tap on the phone stay in the recovery mode and do the following (assuming you are not in the adb shell mode, if so first type exit
):
cd ~/.android
adb push adbkey.pub /data/misc/adb/adb_keys
Hurray, it all should be hunky-dory now! Just reboot the phone and you should be able to access adb when the phone is running:
adb shell reboot
P.S. Was using OS X and Moto X Style that's with the cracked screen.
Say for instance, you do not store the actual variable through the property or use the value to calculate something.
In such case you can either create a method to do your calculation
private void Calculate(int value)
{
//...
}
Or you can do so using
public int MyProperty {get; private set;}
In those cases I would recommend to use the later, as properties refactor each member element intact.
Other than that, if even say you map the property with a Variable. In such a case, within your code you want to write like this :
public int myprop;
public int MyProperty {get { return myprop;}}
... ...
this.myprop = 30;
... ...
if(this.MyProperty > 5)
this.myprop = 40;
The code above looks horrible as the programmer need always cautious to use MyProperty for Get and myprop for Set.
Rether for consistency you can use a Private setter which makes the Propoerty readonly outside while you can use its setter inside in your code.
That solution from the official wiki:
vzctl set $CTID --netfilter full --save
https://openvz.org/VPN_via_the_TUN/TAP_device#Troubleshooting
The quotes you use are the issue:
<meta http-equiv=”refresh” content=”5" >
You should use the "
<meta http-equiv="refresh" content="5">
Notice that if the file's parent folder doesn't exist you'll get the same error:
IOError: [Errno 2] No such file or directory:
Below is another solution which handles this case:
(*) I used sys.stdout
and print
instead of f.write
just to show another use case
# Make sure the file's folder exist - Create folder if doesn't exist
folder_path = 'path/to/'+folder_name+'/'
if not os.path.exists(folder_path):
os.makedirs(folder_path)
print_to_log_file(folder_path, "Some File" ,"Some Content")
Where the internal print_to_log_file
just take care of the file level:
# If you're not familiar with sys.stdout - just ignore it below (just a use case example)
def print_to_log_file(folder_path ,file_name ,content_to_write):
#1) Save a reference to the original standard output
original_stdout = sys.stdout
#2) Choose the mode
write_append_mode = 'a' #Append mode
file_path = folder_path + file_name
if (if not os.path.exists(file_path) ):
write_append_mode = 'w' # Write mode
#3) Perform action on file
with open(file_path, write_append_mode) as f:
sys.stdout = f # Change the standard output to the file we created.
print(file_path, content_to_write)
sys.stdout = original_stdout # Reset the standard output to its original value
Consider the following states:
'w' --> Write to existing file
'w+' --> Write to file, Create it if doesn't exist
'a' --> Append to file
'a+' --> Append to file, Create it if doesn't exist
In your case I would use a different approach and just use 'a'
and 'a+'
.
PID 0 is the System Idle Process, which is surely not listening to port 80. How did you check which process was using the port?
You can use
netstat /nao | findstr "80"
to find the PID and check what process it is.
Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict
In your case, sort the dict by key before plotting,
import matplotlib.pylab as plt
lists = sorted(d.items()) # sorted by key, return a list of tuples
x, y = zip(*lists) # unpack a list of pairs into two tuples
plt.plot(x, y)
plt.show()
Almost all of the replies that people have posted so far only cover how to handle access tokens on the front end, following Instagram's client-side "implicit authentication" procedure. This method is less secure and unrecommended according to Instagram's API docs.
Assuming you are using a server, the Instagram docs sort of fail in providing a clear answer about exchanging a code for a token, as they only give an example of a cURL request. Essentially you have to make a POST request to their server with the provided code and all of your app's information, and they will return a user object including user information and the token.
I don't know what language you are writing in, but I solved this in Node.js with the request npm module which you can find here.
I parsed through the url and used this information to send the post request
var code = req.url.split('code=')[1];
request.post(
{ form: { client_id: configAuth.instagramAuth.clientID,
client_secret: configAuth.instagramAuth.clientSecret,
grant_type: 'authorization_code',
redirect_uri: configAuth.instagramAuth.callbackURL,
code: code
},
url: 'https://api.instagram.com/oauth/access_token'
},
function (err, response, body) {
if (err) {
console.log("error in Post", err)
}else{
console.log(JSON.parse(body))
}
}
);
Of course replace the configAuth stuff with your own information. You probably aren't using Node.js, but hopefully this solution will help you translate your own solution into whatever language you are using it in.
Converting millis to datetime (UTC):
import datetime
time_in_millis = 1596542285000
dt = datetime.datetime.fromtimestamp(time_in_millis / 1000.0, tz=datetime.timezone.utc)
Converting datetime to string following the RFC3339 standard (used by Open API specification):
from rfc3339 import rfc3339
converted_to_str = rfc3339(dt, utc=True, use_system_timezone=False)
# 2020-08-04T11:58:05Z
NOTE: This answer is outdated. It was true at the time it was posted, but no longer is.
Mustache has interpreters in many languages, while Handlebars is Javascript only.
May I suggest the jQuery Media Plugin? Provides embed code for all kinds of video, not just WMV and does browser detection, keeping all that messy switch/case statements out of your templates.
You can also check for socket output stream error while writing to client socket.
out.println(output);
if(out.checkError())
{
throw new Exception("Error transmitting data.");
}
When using Bash just try this:
$ export JAVA_HOME=/usr/tomcat/jre
I believe you can also do it while creating the dialog (copied from a project I did):
dialog = $('#dialog').dialog({
modal: true,
autoOpen: false,
width: 700,
height: 500,
minWidth: 700,
minHeight: 500,
position: ["center", 200],
close: CloseFunction,
overlay: {
opacity: 0.5,
background: "black"
}
});
Note close: CloseFunction
Run java
with -d64
or -d32
specified, it will give you an error message if it doesn't support 64-bit or 32-bit respectively. Your JVM may support both.
At last, Visual Studio 2017 allows the user to import an entire directory with a single click. Visual Studio 2017 has a new functionality "Open Folder" that allows opening the entire folder, even without the need to save it as solution. The source code can be imported using the following methods.
devenv.exe <source folder>
It even supports building and debugging CMake projects.
If you want to replace an empty string and records with only spaces, the correct answer is!:
df = df.replace(r'^\s*$', np.nan, regex=True)
The accepted answer
df.replace(r'\s+', np.nan, regex=True)
Does not replace an empty string!, you can try yourself with the given example slightly updated:
df = pd.DataFrame([
[-0.532681, 'foo', 0],
[1.490752, 'bar', 1],
[-1.387326, 'fo o', 2],
[0.814772, 'baz', ' '],
[-0.222552, ' ', 4],
[-1.176781, 'qux', ''],
], columns='A B C'.split(), index=pd.date_range('2000-01-01','2000-01-06'))
Note, also that 'fo o' is not replaced with Nan, though it contains a space. Further note, that a simple:
df.replace(r'', np.NaN)
Does not work either - try it out.
using Eloquent
$data = array(
array('user_id'=>'Coder 1', 'subject_id'=> 4096),
array('user_id'=>'Coder 2', 'subject_id'=> 2048),
//...
);
Model::insert($data);
Do you have to use a HashMap? If you only need the Map Interface use a TreeMap
If you want to sort by comparing values in the HashMap. You have to write code to do this, if you want to do it once you can sort the values of your HashMap:
Map<String, Person> people = new HashMap<>();
Person jim = new Person("Jim", 25);
Person scott = new Person("Scott", 28);
Person anna = new Person("Anna", 23);
people.put(jim.getName(), jim);
people.put(scott.getName(), scott);
people.put(anna.getName(), anna);
// not yet sorted
List<Person> peopleByAge = new ArrayList<>(people.values());
Collections.sort(peopleByAge, Comparator.comparing(Person::getAge));
for (Person p : peopleByAge) {
System.out.println(p.getName() + "\t" + p.getAge());
}
If you want to access this sorted list often, then you could insert your elements into a HashMap<TreeSet<Person>>
, though the semantics of sets and lists are a bit different.
I stumbled upon the same problem: a page with many independent animations, each one with its own parameters, which must be repeated forever.
Merging this clue with this other clue I found an easy solution: after the end of all your animations the wrapping div
is restored, forcing the animations to restart.
All you have to do is to add these few lines of Javascript, so easy they don't even need any external library, in the <head>
section of your page:
<script>
setInterval(function(){
var container = document.getElementById('content');
var tmp = container.innerHTML;
container.innerHTML= tmp;
}, 35000 // length of the whole show in milliseconds
);
</script>
BTW, the closing </head>
in your code is misplaced: it must be before the starting <body>
.
You need to unicode each element of the list individually
[x.encode('utf-8') for x in tmp]
Another approach in spark 2.1.0
is to use --conf spark.driver.userClassPathFirst=true
during spark-submit which changes the priority of dependency load, and thus the behavior of the spark-job, by giving priority to the jars the user is adding to the class-path with the --jars
option.
public ActionResult Index(string username, string password, string rememberMe)
{
if (!string.IsNullOrEmpty(username))
{
bool remember = bool.Parse(rememberMe);
//...
}
return View();
}
On Windows 10 this worked for me for VIM and VI using git bash
"Esc" + ":wq!"
or
"Esc" + ":q!"
You can use selector
option for dynamic single page applications:
jQuery(function($) {
$(document).tooltip({
selector: '[data-toggle="tooltip"]'
});
});
if a selector is provided, tooltip objects will be delegated to the specified targets. In practice, this is used to enable dynamic HTML content to have tooltips added.
No, it sets all members/elements that haven't been explicitly set to their default-initialisation value, which is zero for numeric types.
throw $e->getMessage();
You try to throw a string
As a sidenote: Exceptions are usually to define exceptional states of the application and not for error messages after validation. Its not an exception, when a user gives you invalid data
The best use case of 'dynamic' type variables for me was when, recently, I was writing a data access layer in ADO.NET (using SQLDataReader) and the code was invoking the already written legacy stored procedures. There are hundreds of those legacy stored procedures containing bulk of the business logic. My data access layer needed to return some sort of structured data to the business logic layer, C# based, to do some manipulations (although there are almost none). Every stored procedures returns different set of data (table columns). So instead of creating dozens of classes or structs to hold the returned data and pass it to the BLL, I wrote the below code which looks quite elegant and neat.
public static dynamic GetSomeData(ParameterDTO dto)
{
dynamic result = null;
string SPName = "a_legacy_stored_procedure";
using (SqlConnection connection = new SqlConnection(DataConnection.ConnectionString))
{
SqlCommand command = new SqlCommand(SPName, connection);
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("@empid", dto.EmpID));
command.Parameters.Add(new SqlParameter("@deptid", dto.DeptID));
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
dynamic row = new ExpandoObject();
row.EmpName = reader["EmpFullName"].ToString();
row.DeptName = reader["DeptName"].ToString();
row.AnotherColumn = reader["AnotherColumn"].ToString();
result = row;
}
}
}
return result;
}
<> means not equal. however, in some versions of SQL, you can write !=
I have been trying out the different packages including the function:
install.packages ("prettyR")
library (prettyR)
delimit.table (Corrvar,"Name the csv.csv")
## Corrvar
is a name of an object from an output I had on scaled variables to run a regression.
However I tried this same code for an output from another analysis (occupancy models model selection output) and it did not work. And after many attempts and exploration I:
In the "Data" vignette, click on "Text to column"
Select Delimited option, click next
Tick space box in "Separator", click next
Click Finalize (End)
Your output now should be in a form you can manipulate easy in excel. So perhaps not the fanciest option but it does the trick if you just want to explore your data in another way.
PS. If the labels in excel are not the exact one it is because Im translating the lables from my spanish excel.
With GNU awk for inplace editing, \s/\S
, and gensub()
to delete
1) the FIRST field:
awk -i inplace '{sub(/^\S+\s*/,"")}1' file
or
awk -i inplace '{$0=gensub(/^\S+\s*/,"",1)}1' file
2) the LAST field:
awk -i inplace '{sub(/\s*\S+$/,"")}1' file
or
awk -i inplace '{$0=gensub(/\s*\S+$/,"",1)}1' file
3) the Nth field where N=3:
awk -i inplace '{$0=gensub(/\s*\S+/,"",3)}1' file
Without GNU awk you need a match()
+substr()
combo or multiple sub()
s + vars to remove a middle field. See also Print all but the first three columns.
I had been facing similar problem in downloading big files this works fine for me now:
safe_mode = off
max_input_time = 9000
memory_limit = 1073741824
post_max_size = 1073741824
file_uploads = On
upload_max_filesize = 1073741824
max_file_uploads = 100
allow_url_fopen = On
Hope this helps.
Well the most used pattern for reusable logic I have come across is either writing a hook or creating a utils file. It depends on what you want to accomplish.
hooks/useForm.js
Like if you want to validate form data then I would create a custom hook named useForm.js and provide it form data and in return it would return me an object containing two things:
Object: {
value,
error,
}
You can definitely return more things from it as you progress.
utils/URL.js
Another example would be like you want to extract some information from a URL then I would create a utils file for it containing a function and import it where needed:
export function getURLParam(p) {
...
}
Before you set your routes, add the code:
app.all('*', function(req, res, next) {
setTimeout(function() {
next();
}, 120000); // 120 seconds
});
The method that you want to run must be a ThreadStart
Delegate. Please consult the Thread
documentation on MSDN. Note that you can sort of create your two-parameter start with a closure. Something like:
var t = new Thread(() => Startup(port, path));
Note that you may want to revisit your method accessibility. If I saw a class starting a thread on its own public method in this manner, I'd be a little surprised.
OQ asked about static string
vs const
. Both have different use cases (although both are treated as static).
Use const only for truly constant values (e.g. speed of light - but even this varies depending on medium). The reason for this strict guideline is that the const value is substituted into the uses of the const in assemblies that reference it, meaning you can have versioning issues should the const change in its place of definition (i.e. it shouldn't have been a constant after all). Note this even affects private const
fields because you might have base and subclass in different assemblies and private fields are inherited.
Static fields are tied to the type they are declared within. They are used for representing values that need to be the same for all instances of a given type. These fields can be written to as many times as you like (unless specified readonly).
If you meant static readonly
vs const
, then I'd recommend static readonly
for almost all cases because it is more future proof.
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.
Here I find the outliers in x
and substitute them with the median of a window of points (win
) around them (taking from Benjamin Bannier answer the median deviation)
def outlier_smoother(x, m=3, win=3, plots=False):
''' finds outliers in x, points > m*mdev(x) [mdev:median deviation]
and replaces them with the median of win points around them '''
x_corr = np.copy(x)
d = np.abs(x - np.median(x))
mdev = np.median(d)
idxs_outliers = np.nonzero(d > m*mdev)[0]
for i in idxs_outliers:
if i-win < 0:
x_corr[i] = np.median(np.append(x[0:i], x[i+1:i+win+1]))
elif i+win+1 > len(x):
x_corr[i] = np.median(np.append(x[i-win:i], x[i+1:len(x)]))
else:
x_corr[i] = np.median(np.append(x[i-win:i], x[i+1:i+win+1]))
if plots:
plt.figure('outlier_smoother', clear=True)
plt.plot(x, label='orig.', lw=5)
plt.plot(idxs_outliers, x[idxs_outliers], 'ro', label='outliers')
plt.plot(x_corr, '-o', label='corrected')
plt.legend()
return x_corr
Basically you need following things to make location detector android app
Now if you write each of these module yourself then it needs much time and efforts. So it would be better to use ready resources that are being maintained already.
Using all these resources, you will be able to create an flawless android location detection app.
You will first need to listen for current location of user. You can use any of below libraries to quick start.
This library provide last known location, location updates
With this library you just need to provide a Configuration object with your requirements, and you will receive a location or a fail reason with all the stuff are described above handled.
Use this open source repo of the Hypertrack Live app to build live location sharing experience within your app within a few hours. HyperTrack Live app helps you share your Live Location with friends and family through your favorite messaging app when you are on the way to meet up. HyperTrack Live uses HyperTrack APIs and SDKs.
Google Maps Android API utility library
If you want to add route maps feature in your apps you can use DrawRouteMaps to make you work more easier. This is lib will help you to draw route maps between two point LatLng.
Simple, smooth animation for route / polylines on google maps using projections. (WIP)
This project allows you to calculate the direction between two locations and display the route on a Google Map using the Google Directions API.
Try out cat
and sprintf
in your for loop.
eg.
cat(sprintf("\"%f\" \"%f\"\n", df$r, df$interest))
See here
If you installed php with homebrew, then check if your apache2.conf file is using homebrew version of php5.so file.
Simply like this:
ALTER TABLE tablename AUTO_INCREMENT = value;
reference: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html
Open SQL Server Management Studio > File > Open > File > Choose your .sql file (the one that contains your script) > Press Open > the file will be opened within SQL Server Management Studio, Now all what you need to do is to press Execute button.
The fundamental reason/problem is that the designers of the CLS specification (which defines how languages interact with .net) did not define a means by which class members could specify that they must be called directly, rather than via callvirt
, without the caller performing a null-reference check; nor did it provide a meany of defining structures which would not be subject to "normal" boxing.
Had the CLS specification defined such a means, then it would be possible for .net to consistently follow the lead established by the Common Object Model (COM), under which a null string reference was considered semantically equivalent to an empty string, and for other user-defined immutable class types which are supposed to have value semantics to likewise define default values. Essentially, what would happen would be for each member of String
, e.g. Length
to be written as something like [InvokableOnNull()] int String Length { get { if (this==null) return 0; else return _Length;} }
. This approach would have offered very nice semantics for things which should behave like values, but because of implementation issues need to be stored on the heap. The biggest difficulty with this approach is that the semantics of conversion between such types and Object
could get a little murky.
An alternative approach would have been to allow the definition of special structure types which did not inherit from Object
but instead had custom boxing and unboxing operations (which would convert to/from some other class type). Under such an approach, there would be a class type NullableString
which behaves as string does now, and a custom-boxed struct type String
, which would hold a single private field Value
of type String
. Attempting to convert a String
to NullableString
or Object
would return Value
if non-null, or String.Empty
if null. Attempting to cast to String
, a non-null reference to a NullableString
instance would store the reference in Value
(perhaps storing null if the length was zero); casting any other reference would throw an exception.
Even though strings have to be stored on the heap, there is conceptually no reason why they shouldn't behave like value types that have a non-null default value. Having them be stored as a "normal" structure which held a reference would have been efficient for code that used them as type "string", but would have added an extra layer of indirection and inefficiency when casting to "object". While I don't foresee .net adding either of the above features at this late date, perhaps designers of future frameworks might consider including them.
You can un-check the build automatically in Project menu and then build by hand by type Ctrl + B, or clicking an icon the appears to the right of the printer icon.
Visible gallery changes visibility which is how you get the gallery over other view overlap. the Home sample app has some good examples of this technique.
addAccordian(type, data) { console.log(type, data);
let form = this.form;
if (!form.controls[type]) {
let ownerAccordian = new FormArray([]);
const group = new FormGroup({});
ownerAccordian.push(
this.applicationService.createControlWithGroup(data, group)
);
form.controls[type] = ownerAccordian;
} else {
const group = new FormGroup({});
(<FormArray>form.get(type)).push(
this.applicationService.createControlWithGroup(data, group)
);
}
console.log(this.form);
}
This works for .Net Core. Call on your Soap client:
client.ClientCredentials.ServiceCertificate.SslCertificateAuthentication =
new X509ServiceCertificateAuthentication()
{
CertificateValidationMode = X509CertificateValidationMode.None,
RevocationMode = X509RevocationMode.NoCheck
};
Under the general heading of 'editors always forget to document getting out…' to toggle go to another line and press the combination ctrl+shift+'N' to erase the current bookmark do the same on marked line…
The goal is to make the <body> element take up the available height of the screen.
If you don't expect your content to take up more than the height of the screen, or you plan to make an inner scrollable element, set
body {
height: 100vh;
}
otherwise, you want <body> to become scrollable when there is more content than the screen can hold, so set
body {
min-height: 100vh;
}
this alone achieves the goal, albeit with a possible, and probably desirable, refinement.
Removing the margin of <body>.
body {
margin: 0;
}
there are two main reasons for doing so.
P.S. if you want the background to be a radial gradient with its center in the center of the screen and not in the bottom right corner as with your example, consider using something like
body {
min-height: 100vh;
margin: 0;
background: radial-gradient(circle, rgba(255,255,255,1) 0%, rgba(0,0,0,1) 100%);
}
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=">
<title>test</title>
</head>
<body>
</body>
</html>
_x000D_
.clock {_x000D_
width: 260px;_x000D_
margin: 0 auto;_x000D_
padding: 30px;_x000D_
color: #FFF;background:#333;_x000D_
}_x000D_
.clock ul {_x000D_
width: 250px;_x000D_
margin: 0 auto;_x000D_
padding: 0;_x000D_
list-style: none;_x000D_
text-align: center_x000D_
}_x000D_
_x000D_
.clock ul li {_x000D_
display: inline;_x000D_
font-size: 3em;_x000D_
text-align: center;_x000D_
font-family: "Arial", Helvetica, sans-serif;_x000D_
text-shadow: 0 2px 5px #55c6ff, 0 3px 6px #55c6ff, 0 4px 7px #55c6ff_x000D_
}_x000D_
#Date { _x000D_
font-family: 'Arial', Helvetica, sans-serif;_x000D_
font-size: 26px;_x000D_
text-align: center;_x000D_
text-shadow: 0 2px 5px #55c6ff, 0 3px 6px #55c6ff;_x000D_
padding-bottom: 40px;_x000D_
}_x000D_
_x000D_
#point {_x000D_
position: relative;_x000D_
-moz-animation: mymove 1s ease infinite;_x000D_
-webkit-animation: mymove 1s ease infinite;_x000D_
padding-left: 10px;_x000D_
padding-right: 10px_x000D_
}_x000D_
_x000D_
/* Animasi Detik Kedap - Kedip */_x000D_
@-webkit-keyframes mymove _x000D_
{_x000D_
0% {opacity:1.0; text-shadow:0 0 20px #00c6ff;}_x000D_
50% {opacity:0; text-shadow:none; }_x000D_
100% {opacity:1.0; text-shadow:0 0 20px #00c6ff; } _x000D_
}_x000D_
_x000D_
@-moz-keyframes mymove _x000D_
{_x000D_
0% {opacity:1.0; text-shadow:0 0 20px #00c6ff;}_x000D_
50% {opacity:0; text-shadow:none; }_x000D_
100% {opacity:1.0; text-shadow:0 0 20px #00c6ff; } _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>_x000D_
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function() {_x000D_
// Making 2 variable month and day_x000D_
var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; _x000D_
var dayNames= ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]_x000D_
_x000D_
// make single object_x000D_
var newDate = new Date();_x000D_
// make current time_x000D_
newDate.setDate(newDate.getDate());_x000D_
// setting date and time_x000D_
$('#Date').html(dayNames[newDate.getDay()] + " " + newDate.getDate() + ' ' + monthNames[newDate.getMonth()] + ' ' + newDate.getFullYear());_x000D_
_x000D_
setInterval( function() {_x000D_
// Create a newDate() object and extract the seconds of the current time on the visitor's_x000D_
var seconds = new Date().getSeconds();_x000D_
// Add a leading zero to seconds value_x000D_
$("#sec").html(( seconds < 10 ? "0" : "" ) + seconds);_x000D_
},1000);_x000D_
_x000D_
setInterval( function() {_x000D_
// Create a newDate() object and extract the minutes of the current time on the visitor's_x000D_
var minutes = new Date().getMinutes();_x000D_
// Add a leading zero to the minutes value_x000D_
$("#min").html(( minutes < 10 ? "0" : "" ) + minutes);_x000D_
},1000);_x000D_
_x000D_
setInterval( function() {_x000D_
// Create a newDate() object and extract the hours of the current time on the visitor's_x000D_
var hours = new Date().getHours();_x000D_
// Add a leading zero to the hours value_x000D_
$("#hours").html(( hours < 10 ? "0" : "" ) + hours);_x000D_
}, 1000); _x000D_
});_x000D_
</script>_x000D_
<div class="clock">_x000D_
<div id="Date"></div>_x000D_
<ul>_x000D_
<li id="hours"></li>_x000D_
<li id="point">:</li>_x000D_
<li id="min"></li>_x000D_
<li id="point">:</li>_x000D_
<li id="sec"></li>_x000D_
</ul>_x000D_
</div>
_x000D_
If you know the aspect ratio for example, if your image is square you can set either the height
or the width
to fill the container and get the other to be set by the aspectRatio
property
Here is the style if you want the height
be set automatically:
{
width: '100%',
height: undefined,
aspectRatio: 1,
}
Note: height
must be undefined
From mathematical point of view both sides are equal.
And you can easily prove this. Let's m=max(x)
. Now your function softmax
returns a vector, whose i-th coordinate is equal to
notice that this works for any m
, because for all (even complex) numbers e^m != 0
from computational complexity point of view they are also equivalent and both run in O(n)
time, where n
is the size of a vector.
from numerical stability point of view, the first solution is preferred, because e^x
grows very fast and even for pretty small values of x
it will overflow. Subtracting the maximum value allows to get rid of this overflow. To practically experience the stuff I was talking about try to feed x = np.array([1000, 5])
into both of your functions. One will return correct probability, the second will overflow with nan
your solution works only for vectors (Udacity quiz wants you to calculate it for matrices as well). In order to fix it you need to use sum(axis=0)
I'm not aware of OpenCV but looking at the problem logically I think you could differentiate between bottle and can by changing the image which you are looking for i.e. Coca Cola. You should incorporate till top portion of can as in case of can there is silver lining at top of coca cola and in case of bottle there will be no such silver lining.
But obviously this algorithm will fail in cases where top of can is hidden, but in such case even human will not be able to differentiate between the two (if only coca cola portion of bottle/can is visible)
Something like:
if(divisor == 0) {
throw new ArithmeticException("Division by zero!");
}
For those who are getting the "Unable to resolve dependencies" error:
Toggle "Offline Mode" off
('View'->Tool Windows->Gradle)
What is the use of e.printStackTrace() method in Java?
Well, the purpose of using this method e.printStackTrace();
is to see what exactly wrong is.
For example, we want to handle an exception. Let's have a look at the following Example.
public class Main{
public static void main(String[] args) {
int a = 12;
int b = 2;
try {
int result = a / (b - 2);
System.out.println(result);
}
catch (Exception e)
{
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
I've used method e.printStackTrace();
in order to show exactly what is wrong.
In the output, we can see the following result.
Error: / by zero
java.lang.ArithmeticException: / by zero
at Main.main(Main.java:10)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Select the Text
From the menu, go to Plugins > NPPExport > Copy RTF to clipboard
In MS Word go to Edit > Paste Special
This will open the Paste Special dialog box. Select the Paste radio button and from the list select Formatted Text (RTF)
You should be able to see the Formatted Text.
this also worked for me , thanks a lot
changing java proxy settings to direct connection did not fix my issue.
What worked for me:
Run "Configure Java" as administrator.
Go to Advanced
Scroll to bottom
Under: "Advanced Security Settings" uncheck "Use SSL 2.0 compatible ClientHello format"
Save
I tried this with Visual Studio 2013 Express, using a pointer instead of an index, which sped up the process a bit. I suspect this is because the addressing is offset + register, instead of offset + register + (register<<3). C++ code.
uint64_t* bfrend = buffer+(size/8);
uint64_t* bfrptr;
// ...
{
startP = chrono::system_clock::now();
count = 0;
for (unsigned k = 0; k < 10000; k++){
// Tight unrolled loop with uint64_t
for (bfrptr = buffer; bfrptr < bfrend;){
count += __popcnt64(*bfrptr++);
count += __popcnt64(*bfrptr++);
count += __popcnt64(*bfrptr++);
count += __popcnt64(*bfrptr++);
}
}
endP = chrono::system_clock::now();
duration = chrono::duration_cast<std::chrono::nanoseconds>(endP-startP).count();
cout << "uint64_t\t" << count << '\t' << (duration/1.0E9) << " sec \t"
<< (10000.0*size)/(duration) << " GB/s" << endl;
}
assembly code: r10 = bfrptr, r15 = bfrend, rsi = count, rdi = buffer, r13 = k :
$LL5@main:
mov r10, rdi
cmp rdi, r15
jae SHORT $LN4@main
npad 4
$LL2@main:
mov rax, QWORD PTR [r10+24]
mov rcx, QWORD PTR [r10+16]
mov r8, QWORD PTR [r10+8]
mov r9, QWORD PTR [r10]
popcnt rdx, rax
popcnt rax, rcx
add rdx, rax
popcnt rax, r8
add r10, 32
add rdx, rax
popcnt rax, r9
add rsi, rax
add rsi, rdx
cmp r10, r15
jb SHORT $LL2@main
$LN4@main:
dec r13
jne SHORT $LL5@main
If you want to access the data in instance B from the instance A. Then this is the query, you can edit your respective credential.
CREATE DATABASE LINK dblink_passport
CONNECT TO xxusernamexx IDENTIFIED BY xxpasswordxx
USING
'(DESCRIPTION=
(ADDRESS=
(PROTOCOL=TCP)
(HOST=xxipaddrxx / xxhostxx )
(PORT=xxportxx))
(CONNECT_DATA=
(SID=xxsidxx)))';
After executing this query access table
SELECT * FROM tablename@dblink_passport;
You can perform any operation DML, DDL, DQL
The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.
If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.
Please try following
if ([ $dateR -ge 234 ] && [ $dateR -lt 238 ]) || ([ $dateR -ge 834 ] && [ $dateR -lt 838 ]) || ([ $dateR -ge 1434 ] && [ $dateR -lt 1438 ]) || ([ $dateR -ge 2034 ] && [ $dateR -lt 2038 ]) ;
then
echo "WORKING"
else
echo "Out of range!"
Recent versions of Mercurial include the evolve
extension which provides the hg amend
command. This allows amending a commit without losing the pre-amend history in your version control.
hg amend [OPTION]... [FILE]...
aliases: refresh
combine a changeset with updates and replace it with a new one
Commits a new changeset incorporating both the changes to the given files and all the changes from the current parent changeset into the repository. See 'hg commit' for details about committing changes. If you don't specify -m, the parent's message will be reused. Behind the scenes, Mercurial first commits the update as a regular child of the current parent. Then it creates a new commit on the parent's parents with the updated contents. Then it changes the working copy parent to this new combined changeset. Finally, the old changeset and its update are hidden from 'hg log' (unless you use --hidden with log).
See https://www.mercurial-scm.org/doc/evolution/user-guide.html#example-3-amend-a-changeset-with-evolve for a complete description of the evolve
extension.
The easier way is through the web management console:
Once you have an image you can launch another cloned instance, data and all. :)
/**********************************************************************
* it will write content to a specified file
*
* @param keyString
* @throws IOException
*********************************************************************/
public static void writeToFile(String keyString,String textFilePAth) throws IOException {
// For output to file
File a = new File(textFilePAth);
if (!a.exists()) {
a.createNewFile();
}
FileWriter fw = new FileWriter(a.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(keyString);
bw.newLine();
bw.close();
}// end of writeToFile()
It is explained well in this Java World article.
Personally, I tend to use interfaces to define interfaces - i.e. parts of the system design that specify how something should be accessed.
It's not uncommon that I will have a class implementing one or more interfaces.
Abstract classes I use as a basis for something else.
The following is an extract from the above mentioned article JavaWorld.com article, author Tony Sintes, 04/20/01
Interface vs. abstract class
Choosing interfaces and abstract classes is not an either/or proposition. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks.
Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. So instead of trying to define that behavior itself, the abstract base class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, Java calls the method defined by the child class.
Many developers forget that a class that defines an abstract method can call that method as well. Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies.
Class vs. interface
Some say you should define all classes in terms of interfaces, but I think recommendation seems a bit extreme. I use interfaces when I see that something in my design will change frequently.
For example, the Strategy pattern lets you swap new algorithms and processes into your program without altering the objects that use them. A media player might know how to play CDs, MP3s, and wav files. Of course, you don't want to hardcode those playback algorithms into the player; that will make it difficult to add a new format like AVI. Furthermore, your code will be littered with useless case statements. And to add insult to injury, you will need to update those case statements each time you add a new algorithm. All in all, this is not a very object-oriented way to program.
With the Strategy pattern, you can simply encapsulate the algorithm behind an object. If you do that, you can provide new media plug-ins at any time. Let's call the plug-in class MediaStrategy. That object would have one method: playStream(Stream s). So to add a new algorithm, we simply extend our algorithm class. Now, when the program encounters the new media type, it simply delegates the playing of the stream to our media strategy. Of course, you'll need some plumbing to properly instantiate the algorithm strategies you will need.
This is an excellent place to use an interface. We've used the Strategy pattern, which clearly indicates a place in the design that will change. Thus, you should define the strategy as an interface. You should generally favor interfaces over inheritance when you want an object to have a certain type; in this case, MediaStrategy. Relying on inheritance for type identity is dangerous; it locks you into a particular inheritance hierarchy. Java doesn't allow multiple inheritance, so you can't extend something that gives you a useful implementation or more type identity.
Once you have the indexPath of your cell, you can do something like:
[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathOfYourCell, nil] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];
In Xcode 4.6 and higher:
[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:@[indexPathOfYourCell] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];
You can set whatever your like as animation effect, of course.
There is a way. $q.all(...
You can check the below stuffs:
The answer by @ajcr explains how the dot
and matmul
(invoked by the @
symbol) differ. By looking at a simple example, one clearly sees how the two behave differently when operating on 'stacks of matricies' or tensors.
To clarify the differences take a 4x4 array and return the dot
product and matmul
product with a 3x4x2 'stack of matricies' or tensor.
import numpy as np
fourbyfour = np.array([
[1,2,3,4],
[3,2,1,4],
[5,4,6,7],
[11,12,13,14]
])
threebyfourbytwo = np.array([
[[2,3],[11,9],[32,21],[28,17]],
[[2,3],[1,9],[3,21],[28,7]],
[[2,3],[1,9],[3,21],[28,7]],
])
print('4x4*3x4x2 dot:\n {}\n'.format(np.dot(fourbyfour,threebyfourbytwo)))
print('4x4*3x4x2 matmul:\n {}\n'.format(np.matmul(fourbyfour,threebyfourbytwo)))
The products of each operation appear below. Notice how the dot product is,
...a sum product over the last axis of a and the second-to-last of b
and how the matrix product is formed by broadcasting the matrix together.
4x4*3x4x2 dot:
[[[232 152]
[125 112]
[125 112]]
[[172 116]
[123 76]
[123 76]]
[[442 296]
[228 226]
[228 226]]
[[962 652]
[465 512]
[465 512]]]
4x4*3x4x2 matmul:
[[[232 152]
[172 116]
[442 296]
[962 652]]
[[125 112]
[123 76]
[228 226]
[465 512]]
[[125 112]
[123 76]
[228 226]
[465 512]]]
For those who tried gkalpak answer and it did not work,
be aware that chrome will add the content script to a needed page only when your extension enabled during chrome launch and also a good idea restart browser after making these changes
I think its the double use of header. I just tried something similar myself and also caused issues. I capitalized my component file to match the others and it worked.
import Header from './src/components/header/header';
Should be
import Header from './src/components/header/Header';
def infinity():
i=0
while True:
i+=1
yield i
for i in infinity():
if there_is_a_reason_to_break(i):
break
Another very subtle cause:
Multi-flavor library should be compiled in specific way than a normal single-flavored. Otherwise it silently produces cannot resolve symbols error.
Multi flavor app based on multi flavor library in Android Gradle
Use its value directly:
In [79]: df[df.c > 0.5][['b', 'e']].values
Out[79]:
array([[ 0.98836259, 0.82403141],
[ 0.337358 , 0.02054435],
[ 0.29271728, 0.37813099],
[ 0.70033513, 0.69919695]])
https://support.google.com/googleplay/android-developer/answer/1078870?hl=en&ref_topic=2897459
PictureBox circle = new PictureBox();
circle.Paint += new PaintEventHandler(circle_Paint);
void circle_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawEllipse(Pens.Red, 0, 0, 30, 30);
}
console.time("myTimer");
console.timeLog("myTimer");
console.timeEnd("myTimer");
You can read more about this on MDN and in the Node.js documentation.
Available on Chrome, Firefox, Opera and NodeJS. (not on Edge or Internet Explorer).
One solution would be to divide your table into 20 columns of 5% width each, then use colspan on each real column to get the desired width, like this:
<html>_x000D_
<body bgcolor="#14B3D9">_x000D_
<table width="100%" border="1" bgcolor="#ffffff">_x000D_
<colgroup>_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
</colgroup>_x000D_
<tr>_x000D_
<td colspan=5>25</td>_x000D_
<td colspan=10>50</td>_x000D_
<td colspan=5>25</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td colspan=10>50</td>_x000D_
<td colspan=6>30</td>_x000D_
<td colspan=4>20</td>_x000D_
</tr>_x000D_
</table>_x000D_
</body>_x000D_
</html>
_x000D_
Another way to solve this kind of error is to start eclipse with this argument
-vmargs -Djava.net.preferIPv4Stack=true
Working fine with Eclipse (x64) 4.3.1
This error tells you everything:
undefined reference toHash::insert(int, char)
You're not linking with the implementations of functions defined in Hash.h
. Don't you have a Hash.cpp
to also compile and link?
To check if this extensions are enabled or not, you can create a php file i.e. info.php
and write the following code there:
<?php
echo "GD: ", extension_loaded('gd') ? 'OK' : 'MISSING', '<br>';
echo "XML: ", extension_loaded('xml') ? 'OK' : 'MISSING', '<br>';
echo "zip: ", extension_loaded('zip') ? 'OK' : 'MISSING', '<br>';
?>
That's it.
Another cause of "TCP ACKed Unseen" is the number of packets that may get dropped in a capture. If I run an unfiltered capture for all traffic on a busy interface, I will sometimes see a large number of 'dropped' packets after stopping tshark.
On the last capture I did when I saw this, I had 2893204 packets captured, but once I hit Ctrl-C, I got a 87581 packets dropped message. Thats a 3% loss, so when wireshark opens the capture, its likely to be missing packets and report "unseen" packets.
As I mentioned, I captured a really busy interface with no capture filter, so tshark had to sort all packets, when I use a capture filter to remove some of the noise, I no longer get the error.
why can't you put the code behind a promise? (typed in off the top of my head)
new Promise(function(resolve, reject) {_x000D_
setTimeout(resolve, 2000);_x000D_
}).then(function() {_x000D_
console.log('do whatever you wanted to hold off on');_x000D_
});
_x000D_
var array = (new Function("return [" + str+ "];")());
var string = "0,1";
var objectstring = '{Name:"Tshirt", CatGroupName:"Clothes", Gender:"male-female"}, {Name:"Dress", CatGroupName:"Clothes", Gender:"female"}, {Name:"Belt", CatGroupName:"Leather", Gender:"child"}';
var stringArray = (new Function("return [" + string+ "];")());
var objectStringArray = (new Function("return [" + objectstring+ "];")());
JSFiddle https://jsfiddle.net/7ne9L4Lj/1/
- JSON.parse("[" + string + "]"); // throw error
- string.split(",")
// unexpected result
["{Name:"Tshirt"", " CatGroupName:"Clothes"", " Gender:"male-female"}", " {Name:"Dress"", " CatGroupName:"Clothes"", " Gender:"female"}", " {Name:"Belt"", " CatGroupName:"Leather"", " Gender:"child"}"]
This goes for both negative and positive intigers
int get_len(int n)
{
if(n == 0)
return 1;
if(n < 0)
{
n = n * (-1); // if negative
}
return log10(n) + 1;
}
Same logic goes for loop
int get_len(int n)
{
if(n == 0)
return 1;
int len = 0;
if(n < 0)
n = n * (-1);
while(n > 1)
{
n /= 10;
len++;
}
return len;
}
code to select dropdown using xpath
Select select = new
Select(driver.findElement(By.xpath("//select[@id='periodId']));
code to select particaular option using selectByVisibleText
select.selectByVisibleText(Last 52 Weeks);
Seems like looking for something specific to the installed program would work better, but HKCU\Software and HKLM\Software are the spots to look.
public class Example extends JFrame {
public static final int WIDTH = 550;//Any Size
public static final int HEIGHT = 335;//Any Size
public Example(){
init();
}
private void init() {
try {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
SwingUtilities.updateComponentTreeUI(this);
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
setSize(WIDTH, HEIGHT);
setLocation((int) (dimension.getWidth() / 2 - WIDTH / 2),
(int) (dimension.getHeight() / 2 - HEIGHT / 2));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
}
}
You can do almost the same yourself. Open Environment Variables and click "New" Button in the "User Variables for ..." .
Variable Name: ~
Variable Value: Click "Browse Directory..." button and choose a directory which you want.
And after this, open cmd and type this:
cd %~%
. It works.
You can check if it can be converted to decimal. If yes, then its a number
from decimal import Decimal
def is_number(value):
try:
value = Decimal(value)
return True
except:
return False
print is_number(None) // False
print is_number(0) // True
print is_number(2.3) // True
print is_number('2.3') // True (caveat!)
Ok after a whole productive day down the drain I got it to work.
First I uninstalled all traces of Genymotion and Virtualbox. I then proceeded to install Genymotion and then Virtual Box again, but the previous version (4.2.18)
I ran Genymotion, Downloaded an Image, I got an error message about the network trying to run it. So I ran it Directly inside Virtual Box, It started up 100% with network and everything. I shut it down, went to Image's settings and changed the first adapter to "Host-only".
I opened the Genymotion Launcher again and "Played" my device and it started up with no problems.
Looking at your filenames, have you considered using a build tool like NAnt or Ant (the Java version). You'll get a lot more control than with bat files.
Could be because of restoring SQL Server 2012 version backup file into SQL Server 2008 R2 or even less.
Probably because the original version of Python (CPython) was written in C, not C++.
The idea that a list is formed by pushing things onto the back of something is probably not as well-known as the thought of appending them.
If you want to write bytes then you should open the file in binary mode.
f = open('/tmp/output', 'wb')
You can simply use the pandas.DataFrame.transform1 function in this way:
df.transform(lambda x: x/x.max())
Without root, you can use debug proxies like Charlesproxy&Co.
no lambda method
# sort dictionary by value
d = {'a1': 'fsdfds', 'g5': 'aa3432ff', 'ca':'zz23432'}
def getkeybyvalue(d,i):
for k, v in d.items():
if v == i:
return (k)
sortvaluelist = sorted(d.values())
sortresult ={}
for i1 in sortvaluelist:
key = getkeybyvalue(d,i1)
sortresult[key] = i1
print ('=====sort by value=====')
print (sortresult)
print ('=======================')
Instead of getting the same video player to load new files, why not erase the entire <video>
element and recreate it. Most browsers will automatically load it if the src's are correct.
Example (using Prototype):
var vid = new Element('video', { 'autoplay': 'autoplay', 'controls': 'controls' });
var src = new Element('source', { 'src': 'video.ogg', 'type': 'video/ogg' });
vid.update(src);
src.insert({ before: new Element('source', { 'src': 'video.mp4', 'type': 'video/mp4' }) });
$('container_div').update(vid);
BTW, HTTP 1/1 specification (RFC2616) suggests no more than 2 connections per server.
Clients that use persistent connections SHOULD limit the number of simultaneous connections that they maintain to a given server. A single-user client SHOULD NOT maintain more than 2 connections with any server or proxy. A proxy SHOULD use up to 2*N connections to another server or proxy, where N is the number of simultaneously active users. These guidelines are intended to improve HTTP response times and avoid congestion.
the source to the ssl version of this is here: http://atmospherian.wordpress.com/downloads/
It is a way to simplify error checking and avoid deep nested if's. For example:
do {
// do something
if (error) {
break;
}
// do something else
if (error) {
break;
}
// etc..
} while (0);
I find it much easier to "extend" via assigning in a bigger matrix. E.g.
import numpy as np
p = np.array([[1,2], [3,4]])
g = np.array(range(20))
g.shape = (4,5)
g[0:2, 0:2] = p
Here are the arrays:
p
array([[1, 2],
[3, 4]])
g
:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
and the resulting g
after assignment:
array([[ 1, 2, 2, 3, 4],
[ 3, 4, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
here's what six is:
pip search six
six - Python 2 and 3 compatibility utilities
to install:
pip install six
though if you did install python-dateutil
from pip six should have been set as a dependency.
N.B.: to install pip run easy_install pip
from command line.
Actually there are some cases that above answers would break. Such as wrongly input value, wrongly input range, negative input/output ranges.
def remap( x, oMin, oMax, nMin, nMax ):
#range check
if oMin == oMax:
print "Warning: Zero input range"
return None
if nMin == nMax:
print "Warning: Zero output range"
return None
#check reversed input range
reverseInput = False
oldMin = min( oMin, oMax )
oldMax = max( oMin, oMax )
if not oldMin == oMin:
reverseInput = True
#check reversed output range
reverseOutput = False
newMin = min( nMin, nMax )
newMax = max( nMin, nMax )
if not newMin == nMin :
reverseOutput = True
portion = (x-oldMin)*(newMax-newMin)/(oldMax-oldMin)
if reverseInput:
portion = (oldMax-x)*(newMax-newMin)/(oldMax-oldMin)
result = portion + newMin
if reverseOutput:
result = newMax - portion
return result
#test cases
print remap( 25.0, 0.0, 100.0, 1.0, -1.0 ), "==", 0.5
print remap( 25.0, 100.0, -100.0, -1.0, 1.0 ), "==", -0.25
print remap( -125.0, -100.0, -200.0, 1.0, -1.0 ), "==", 0.5
print remap( -125.0, -200.0, -100.0, -1.0, 1.0 ), "==", 0.5
#even when value is out of bound
print remap( -20.0, 0.0, 100.0, 0.0, 1.0 ), "==", -0.2
You probably need to wrap the UNION
in a sub-SELECT
and apply the WHERE
clause afterward:
SELECT * FROM (
SELECT * FROM Table1 WHERE Field1 = Value1
UNION
SELECT * FROM Table2 WHERE Field1 = Value2
) AS t WHERE Field2 = Value3
Basically, the UNION
is looking for two complete SELECT
statements to combine, and the WHERE
clause is part of the SELECT
statement.
It may make more sense to apply the outer WHERE
clause to both of the inner queries. You'll probably want to benchmark the performance of both approaches and see which works better for you.
Because both a
and b
have only one axis, as their shape is (3)
, and the axis parameter specifically refers to the axis of the elements to concatenate.
this example should clarify what concatenate
is doing with axis. Take two vectors with two axis, with shape (2,3)
:
a = np.array([[1,5,9], [2,6,10]])
b = np.array([[3,7,11], [4,8,12]])
concatenates along the 1st axis (rows of the 1st, then rows of the 2nd):
np.concatenate((a,b), axis=0)
array([[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11],
[ 4, 8, 12]])
concatenates along the 2nd axis (columns of the 1st, then columns of the 2nd):
np.concatenate((a, b), axis=1)
array([[ 1, 5, 9, 3, 7, 11],
[ 2, 6, 10, 4, 8, 12]])
to obtain the output you presented, you can use vstack
a = np.array([1,2,3])
b = np.array([4,5,6])
np.vstack((a, b))
array([[1, 2, 3],
[4, 5, 6]])
You can still do it with concatenate
, but you need to reshape them first:
np.concatenate((a.reshape(1,3), b.reshape(1,3)))
array([[1, 2, 3],
[4, 5, 6]])
Finally, as proposed in the comments, one way to reshape them is to use newaxis
:
np.concatenate((a[np.newaxis,:], b[np.newaxis,:]))
Hi we can use default method "first" in jQuery
Here some examples:
When you want to add class for first div
$('.alldivs div').first().addClass('active');
When you want to change the remove the "onediv" class and add only to first child
$('.alldivs div').removeClass('onediv').first().addClass('onediv');
To store the array values in cookie, first you need to convert them to string, so here is some options.
Storing code
setcookie('your_cookie_name', json_encode($info), time()+3600);
Reading code
$data = json_decode($_COOKIE['your_cookie_name'], true);
JSON can be good choose also if you need read cookie in front end with JavaScript.
Actually you can use any encrypt_array_to_string
/decrypt_array_from_string
methods group that will convert array to string and convert string back to same array.
For example you can also use explode
/implode
for array of integers.
From PHP.net
Do not pass untrusted user input to unserialize().
- Anything that coming by HTTP including cookies is untrusted!
References related to security
setcookie('my_array[0]', 'value1' , time()+3600);
setcookie('my_array[1]', 'value2' , time()+3600);
setcookie('my_array[2]', 'value3' , time()+3600);
And after if you will print $_COOKIE
variable, you will see the following
echo '<pre>';
print_r( $_COOKIE );
die();
Array ( [my_array] => Array ( [0] => value1 [1] => value2 [2] => value3 ) )
This is documented PHP feature.
From PHP.net
Cookies names can be set as array names and will be available to your PHP scripts as arrays but separate cookies are stored on the user's system.
<TextBlock Margin="4" TextWrapping="Wrap" FontFamily="Verdana" FontSize="12">
<Run TextDecorations="StrikeThrough"> Run cannot contain inline</Run>
<Span FontSize="16"> Span can contain Run or Span or whatever
<LineBreak />
<Bold FontSize="22" FontFamily="Times New Roman" >Bold can contains
<Italic>Italic</Italic></Bold></Span>
</TextBlock>
Some answers already pointed out background-size: cover
is useful in the case, but none points out the browser support details. Here it is:
Add this CSS into your stylesheet:
body {
background: url(background.jpg) no-repeat center center fixed;
background-size: cover; /* for IE9+, Safari 4.1+, Chrome 3.0+, Firefox 3.6+ */
-webkit-background-size: cover; /* for Safari 3.0 - 4.0 , Chrome 1.0 - 3.0 */
-moz-background-size: cover; /* optional for Firefox 3.6 */
-o-background-size: cover; /* for Opera 9.5 */
margin: 0; /* to remove the default white margin of body */
padding: 0; /* to remove the default white margin of body */
}
-moz-background-size: cover;
is optional for Firefox, as Firefox starts supporting the value cover
since version 3.6. If you need to support Konqueror 3.5.4+ as well, add -khtml-background-size: cover;
.
As you're using CSS3, it's suggested to change your DOCTYPE to HTML5. Also, HTML5 CSS Reset stylesheet is suggested to be added BEFORE your our stylesheet to provide a consistent look & feel for modern browsers.
Reference: background-size at MDN
If you ever need to support old browsers like IE 8 or below, you can still go for Javascript way (scroll down to jQuery section)
Last, if you predict your users will use mobile phones to browse your website, do not use the same background image for mobile web, as your desktop image is probably large in file size, which will be a burden to mobile network usage. Use media query to branch CSS.
If you want to really get only "path" without querystring, you can use url
library to parse and get only path part of url.
var url = require('url');
//auth required or redirect
app.use('/account', function(req, res, next) {
var path = url.parse(req.url).pathname;
if ( !req.session.user ) {
res.redirect('/login?ref='+path);
} else {
next();
}
});
:not
selector:
input:not([type]), input[type='text'], input[type='password'] {
/* style here */
}
Support: in Internet Explorer 9 and higher
In CSharp, If you create the method/function outline with it's Parms, then when you add the three forward slashes it will auto generate the summary and parms section.
So I put in:
public string myMethod(string sImput1, int iInput2)
{
}
I then put the three /// before it and Visual Studio's gave me this:
/// <summary>
///
/// </summary>
/// <param name="sImput1"></param>
/// <param name="iInput2"></param>
/// <returns></returns>
public string myMethod(string sImput1, int iInput2)
{
}
mapfile
and readarray
(which are synonymous) are available in Bash version 4 and above. If you have an older version of Bash, you can use a loop to read the file into an array:
arr=()
while IFS= read -r line; do
arr+=("$line")
done < file
In case the file has an incomplete (missing newline) last line, you could use this alternative:
arr=()
while IFS= read -r line || [[ "$line" ]]; do
arr+=("$line")
done < file
Related:
If none of the above answers worked for you, You can try the following solution which worked for me.
Go to Services manager(services.msc) and enable the below services and try again.
- WLAN AutoConfig
- Wi-Fi Direct Services Connection Manager Service
Hope this solved your problem.
The best way to load an image is through the ImageIO
API
BufferedImage img = ImageIO.read(new File("/path/to/some/image"));
There are a number of ways you can render an image to the screen.
You could use a JLabel
. This is the simplest method if you don't want to modify the image in anyway...
JLabel background = new JLabel(new ImageIcon(img));
Then simply add it to your window as you see fit. If you need to add components to it, then you can simply set the label's layout manager to whatever you need and add your components.
If, however, you need something more sophisticated, need to change the image somehow or want to apply additional effects, you may need to use custom painting.
First cavert: Don't ever paint directly to a top level container (like JFrame
). Top level containers aren't double buffered, so you may end up with some flashing between repaints, other objects live on the window, so changing it's paint process is troublesome and can cause other issues and frames have borders which are rendered inside the viewable area of the window...
Instead, create a custom component, extending from something like JPanel
. Override it's paintComponent
method and render your output to it, for example...
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, this);
}
Take a look at Performing Custom Painting and 2D Graphics for more details
I dont think i found the answer in all the above solutions.
Some are also wrong.
To tests if a variable (or an element of an array, or a property of an object) exists (and is not null) use:
echo isset($address['street2']) ? $address['street2'] : 'Empty';
To tests if a variable (...) contains some non-empty data use:
echo !empty($address['street2']) ? $address['street2'] : 'Empty';
There's another very simple answer which can work for some simple graphs.
Just add a call to guide_legend() into your graph.
ggplot(...) + ... + guide_legend(title="my awesome title")
As shown in the very nice ggplot docs.
If that doesn't work, you can more precisely set your guide parameters with a call to guides:
ggplot(...) + ... + guides(fill=guide_legend("my awesome title"))
You can also vary the shape/color/size by specifying these parameters for your call to guides
as well.
This expression
SELECT (((DATEPART(DW, @my_date_var) - 1 ) + @@DATEFIRST ) % 7)
will always return a number between 0 and 6 where
0 -> Sunday
1 -> Monday
2 -> Tuesday
3 -> Wednesday
4 -> Thursday
5 -> Friday
6 -> Saturday
Independently from @@DATEFIRST
So a weekend day is tested like this
SELECT (CASE
WHEN (((DATEPART(DW, @my_date_var) - 1 ) + @@DATEFIRST ) % 7) IN (0,6)
THEN 1
ELSE 0
END) AS is_weekend_day
you can use /<code>([\s\S]*)<\/code>/msU
this catch NEWLINES too!
Don't forget to change profile in Provision Profile sections:
Ideally you should see Automatic
in Code Signing Identity
after you choose provision profile you need. If you don't see any option that's mean you don't have private key for current provision profile.
package com.vipul;
import java.applet.Applet;
import java.awt.Checkbox;
import java.awt.Choice;
import java.awt.Font;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class BatchExecuteService extends Applet {
public Choice choice;
public void init()
{
setFont(new Font("Helvetica", Font.BOLD, 36));
choice = new Choice();
}
public static void main(String[] args) {
BatchExecuteService batchExecuteService = new BatchExecuteService();
batchExecuteService.run();
}
List<String> processList = new ArrayList<String>();
public void run() {
try {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("D:\\server.bat");
process.getOutputStream().close();
InputStream inputStream = process.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(
inputStream);
BufferedReader bufferedrReader = new BufferedReader(
inputstreamreader);
BufferedReader bufferedrReader1 = new BufferedReader(
inputstreamreader);
String strLine = "";
String x[]=new String[100];
int i=0;
int t=0;
while ((strLine = bufferedrReader.readLine()) != null)
{
// System.out.println(strLine);
String[] a=strLine.split(",");
x[i++]=a[0];
}
// System.out.println("Length : "+i);
for(int j=2;j<i;j++)
{
System.out.println(x[j]);
}
}
catch (IOException ioException)
{
ioException.printStackTrace();
}
}
}
You can create batch file like
TASKLIST /v /FI "STATUS eq running" /FO "CSV" /FI "Username eq LHPL002\soft" /FI "MEMUSAGE gt 10000" /FI "Windowtitle ne N/A" /NH
In my case, it was due to Same Origin policies. To explain it further, MDN states the following:
If the iframe and the iframe's parent document are Same Origin, returns a Document (that is, the active document in the inline frame's nested browsing context), else returns null.
My simple fix to stop it putting speech marks around numeric values...
while($r = mysql_fetch_assoc($rs)){
while($elm=each($r))
{
if(is_numeric($r[$elm["key"]])){
$r[$elm["key"]]=intval($r[$elm["key"]]);
}
}
$rows[] = $r;
}
I have tried to run same program using eclipse and it shows clear difference between memcpy
and memmove
. memcpy()
doesn't care about overlapping of memory location which results in corruption of data, while memmove()
will copy data to temporary variable first and then copy into actual memory location.
While trying to copy data from location str1
to str1+2
, output of memcpy
is "aaaaaa
". The question would be how?
memcpy()
will copy one byte at a time from left to right. As shown in your program "aabbcc
" then
all copying will take place as below,
aabbcc -> aaabcc
aaabcc -> aaaacc
aaaacc -> aaaaac
aaaaac -> aaaaaa
memmove()
will copy data to temporary variable first and then copy to actual memory location.
aabbcc(actual) -> aabbcc(temp)
aabbcc(temp) -> aaabcc(act)
aabbcc(temp) -> aaaacc(act)
aabbcc(temp) -> aaaabc(act)
aabbcc(temp) -> aaaabb(act)
Output is
memcpy
: aaaaaa
memmove
: aaaabb
Use this function begining from SQL SERVER 2016
Select Count(value) From STRING_SPLIT('AAA AAA AAA',' ');
-- Output : 3
When This function used with count function it gives you how many character exists in string
I just posted a kind of a RFC that might help you: Split a vector into chunks in R
x = data.frame(num = 1:26, let = letters, LET = LETTERS)
## number of chunks
n <- 2
dfchunk <- split(x, factor(sort(rank(row.names(x))%%n)))
dfchunk
$`0`
num let LET
1 1 a A
2 2 b B
3 3 c C
4 4 d D
5 5 e E
6 6 f F
7 7 g G
8 8 h H
9 9 i I
10 10 j J
11 11 k K
12 12 l L
13 13 m M
$`1`
num let LET
14 14 n N
15 15 o O
16 16 p P
17 17 q Q
18 18 r R
19 19 s S
20 20 t T
21 21 u U
22 22 v V
23 23 w W
24 24 x X
25 25 y Y
26 26 z Z
Cheers, Sebastian
String
values are not implementation dependent, according the ECMA-262 3rd Edition Specification, each character represents a single 16-bit unit of UTF-16 text:
4.3.16 String Value
A string value is a member of the type String and is a finite ordered sequence of zero or more 16-bit unsigned integer values.
NOTE Although each value usually represents a single 16-bit unit of UTF-16 text, the language does not place any restrictions or requirements on the values except that they be 16-bit unsigned integers.
In lieu of a python goto equivalent I use the break statement in the following fashion for quick tests of my code. This assumes you have structured code base. The test variable is initialized at the start of your function and I just move the "If test: break" block to the end of the nested if-then block or loop I want to test, modifying the return variable at the end of the code to reflect the block or loop variable I'm testing.
def x:
test = True
If y:
# some code
If test:
break
return something
I'm crossposting my answer from another question here since it is related and also seems to solve the problem in the question.
Here is my example project with OpenJDK 12, JavaFX 12 and Gradle 5.4
I hope somebody finds the Github project useful.
Additionally below are instructions that work with the Gradle Scala plugin, but don't seem work with Java. I'm leaving this here in case somebody else is also using Scala, Gradle and JavaFX.
1) As mentioned in the question, the JavaFX Gradle plugin needs to be set up. Open JavaFX has detailed documentation on this
2) Additionally you need the the JavaFX SDK for your platform unzipped somewhere. NOTE: Be sure to scroll down to Latest releases section where JavaFX 12 is (LTS 11 is first for some reason.)
3) Then, in IntelliJ you go to the File -> Project Structure -> Libraries
, hit the ?-button and add the lib
folder from the unzipped JavaFX SDK.
For longer instructions with screenshots, check out the excellent Open JavaFX docs for IntelliJ I can't get a deep link working, so select JavaFX and IntelliJ
and then Modular from IDE
from the docs nav. Then scroll down to step 3. Create a library
. Consider checking the other steps too if you are having trouble.
It is difficult to say if this is exactly the same situation as in the original question, but it looked similar enough that I landed here, so I'm adding my experience here to help others.
To get the root view defined in your xml file, without action bar, you can use this:
View root = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
So, to change color to white:
root.setBackgroundResource(Color.WHITE);
My solution is create a Pipe for return the values array or propierties object
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'valueArray',
})
export class ValueArrayPipe implements PipeTransform {
// El parametro object representa, los valores de las propiedades o indice
transform(objects : any = []) {
return Object.values(objects);
}
}
The template Implement
<button ion-item *ngFor="let element of element_list | valueArray" >
{{ element.any_property }}
</button>
detect two fingers pinch zoom on any element, easy and w/o hassle with 3rd party libs like Hammer.js (beware, hammer has issues with scrolling!)
function onScale(el, callback) {
let hypo = undefined;
el.addEventListener('touchmove', function(event) {
if (event.targetTouches.length === 2) {
let hypo1 = Math.hypot((event.targetTouches[0].pageX - event.targetTouches[1].pageX),
(event.targetTouches[0].pageY - event.targetTouches[1].pageY));
if (hypo === undefined) {
hypo = hypo1;
}
callback(hypo1/hypo);
}
}, false);
el.addEventListener('touchend', function(event) {
hypo = undefined;
}, false);
}
Very old question, but I've written some example just for fun — maybe you'll find it useful ;)
#import "InitAllocNewTest.h"
@implementation InitAllocNewTest
+(id)alloc{
NSLog(@"Allocating...");
return [super alloc];
}
-(id)init{
NSLog(@"Initializing...");
return [super init];
}
@end
In main function both statements:
[[InitAllocNewTest alloc] init];
and
[InitAllocNewTest new];
result in the same output:
2013-03-06 16:45:44.125 XMLTest[18370:207] Allocating... 2013-03-06 16:45:44.128 XMLTest[18370:207] Initializing...
/Users/{user}/Library/Application Support/Sublime Text 2/Packages
Get to it quickly from within Sublime via the menu at Sublime Text 2... Preferences... Browse Packages
If you want to pause then use java.util.concurrent.TimeUnit
:
TimeUnit.SECONDS.sleep(1);
To sleep for one second or
TimeUnit.MINUTES.sleep(1);
To sleep for a minute.
As this is a loop, this presents an inherent problem - drift. Every time you run code and then sleep you will be drifting a little bit from running, say, every second. If this is an issue then don't use sleep
.
Further, sleep
isn't very flexible when it comes to control.
For running a task every second or at a one second delay I would strongly recommend a ScheduledExecutorService
and either scheduleAtFixedRate
or scheduleWithFixedDelay
.
For example, to run the method myTask
every second (Java 8):
public static void main(String[] args) {
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(App::myTask, 0, 1, TimeUnit.SECONDS);
}
private static void myTask() {
System.out.println("Running");
}
And in Java 7:
public static void main(String[] args) {
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
myTask();
}
}, 0, 1, TimeUnit.SECONDS);
}
private static void myTask() {
System.out.println("Running");
}
Because that gtab82 table isn't in your FROM or JOIN clause. You refer gtab82 table in these cases: gtab82.memno and gtab82.memacid
You just use the method
public Object put(Object key, Object value)
if the key was already present in the Map then the previous value is returned.
I was working with Live Server and lots stuff stuck. I try many things to fix but exact issue of 255 don't figure out.
Even I had resolved issue 100%
Replace my sshd_config file from similar other my debian server
[email protected]:~# cp sshd_config sshd_config.snippetbucket.com.bkp #keep my backup file
[email protected]:~# echo "" > sshd_config
[email protected]:~# nano sshd_config #replaced all content with other exact same server
[email protected]:~# sudo service ssh restart #normally restart server
That's 100% resolve my issue immediate.
#SnippetBucket-Tip: Always take backup of ssh related files, which help on quick restoration.
Note: After apply given changes you need to exit rescue mode and reboot your vps / dedicated server normally, than your ssh connection works.
During rescue mode ssh don't allow user to login as normally. only rescue ssh related login and password works.
Date today = new Date();
today.setHours(0); //same for minutes and seconds
Since the methods are deprecated, you can do this with Calendar
:
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 0); // same for minutes and seconds
And if you need a Date
object in the end, simply call today.getTime()
// This code was tested by me (Helio Barbosa)
// this directory (../backup) is for try only.
// it is necessary create it and put files into him.
$hDir = '../backup';
if ($handle = opendir( $hDir )) {
echo "Manipulador de diretório: $handle\n";
echo "Arquivos:\n";
/* Esta é a forma correta de varrer o diretório */
/* Here is the correct form to do find files into the directory */
while (false !== ($file = readdir($handle))) {
// echo($file . "</br>");
$filepath = $hDir . "/" . $file ;
// echo( $filepath . "</br>" );
if(is_file($filepath))
{
echo("Deleting:" . $file . "</br>");
unlink($filepath);
}
}
closedir($handle);
}
Make sure that the keys you use to encrypt and decrypt are the same. The padding method even if not explicitly set should still allow for proper decryption/encryption (if not set they will be the same). However if you for some reason are using a different set of keys for decryption than used for encryption you will get this error:
Padding is invalid and cannot be removed
If you are using some algorithm to dynamically generate keys that will not work. They need to be the same for both encryption and decryption. One common way is to have the caller provide the keys in the constructor of the encryption methods class, to prevent the encryption/decryption process having any hand in creation of these items. It focuses on the task at hand (encrypting and decrypting data) and requires the iv
and key
to be supplied by the caller.
As per this answer over here: str='foo%20%5B12%5D'
encodes foo [12]
:
%20 is space
%5B is '['
and %5D is ']'
This is called percent encoding and is used in encoding special characters in the url parameter values.
EDIT By the way as I was reading https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURI#Description, it just occurred to me why so many people make the same search. See the note on the bottom of the page:
Also note that if one wishes to follow the more recent RFC3986 for URL's, making square brackets reserved (for IPv6) and thus not encoded when forming something which could be part of a URL (such as a host), the following may help.
function fixedEncodeURI (str) {
return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']');
}
Hopefully this will help people sort out their problems when they stumble upon this question.
DISTINCT
to remove duplicate GROUPING SETS
from the GROUP BY
clauseIn a completely silly example using GROUPING SETS()
in general (or the special grouping sets ROLLUP()
or CUBE()
in particular), you could use DISTINCT
in order to remove the duplicate values produced by the grouping sets again:
SELECT DISTINCT actors
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY CUBE(actors, actors)
With DISTINCT
:
actors
------
NULL
a
b
Without DISTINCT
:
actors
------
a
b
NULL
a
b
a
b
But why, apart from making an academic point, would you do that?
DISTINCT
to find unique aggregate function valuesIn a less far-fetched example, you might be interested in the DISTINCT
aggregated values, such as, how many different duplicate numbers of actors are there?
SELECT DISTINCT COUNT(*)
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY actors
Answer:
count
-----
2
DISTINCT
to remove duplicates with more than one GROUP BY
columnAnother case, of course, is this one:
SELECT DISTINCT actors, COUNT(*)
FROM (VALUES('a', 1), ('a', 1), ('b', 1), ('b', 2)) t(actors, id)
GROUP BY actors, id
With DISTINCT
:
actors count
-------------
a 2
b 1
Without DISTINCT
:
actors count
-------------
a 2
b 1
b 1
For more details, I've written some blog posts, e.g. about GROUPING SETS
and how they influence the GROUP BY
operation, or about the logical order of SQL operations (as opposed to the lexical order of operations).
(Using system.IO)
You can simply use \n
for newline and \t
in front of the string to indent it.
For example in c#
:
public string theXML() {
string xml = "";
xml += "<Scene>\n";
xml += "\t<Character>\n";
xml += "\t</Character>\n";
xml += "</Scene>\n";
return xml;
}
This will result in the output: http://prntscr.com/96dfqc
Unless you redirect stdout and stderr as the accepted answer suggests, this is not possible with execSync or spawnSync. Without redirecting stdout and stderr those commands only return stdout and stderr when the command is completed.
To do this without redirecting stdout and stderr, you are going to need to use spawn to do this but it's pretty straight forward:
var spawn = require('child_process').spawn;
//kick off process of listing files
var child = spawn('ls', ['-l', '/']);
//spit stdout to screen
child.stdout.on('data', function (data) { process.stdout.write(data.toString()); });
//spit stderr to screen
child.stderr.on('data', function (data) { process.stdout.write(data.toString()); });
child.on('close', function (code) {
console.log("Finished with code " + code);
});
I used an ls command that recursively lists files so that you can test it quickly. Spawn takes as first argument the executable name you are trying to run and as it's second argument it takes an array of strings representing each parameter you want to pass to that executable.
However, if you are set on using execSync and can't redirect stdout or stderr for some reason, you can open up another terminal like xterm and pass it a command like so:
var execSync = require('child_process').execSync;
execSync("xterm -title RecursiveFileListing -e ls -latkR /");
This will allow you to see what your command is doing in the new terminal but still have the synchronous call.
Why not add a variable for the element's Id and make it a reusable function?
function SelectElement(selectElementId, valueToSelect)
{
var element = document.getElementById(selectElementId);
element.value = valueToSelect;
}
The imshow()
function with parameters interpolation='nearest'
and cmap='hot'
should do what you want.
import matplotlib.pyplot as plt
import numpy as np
a = np.random.random((16, 16))
plt.imshow(a, cmap='hot', interpolation='nearest')
plt.show()
For #outer
height to be based on its content, and have #inner
base its height on that, make both elements absolutely positioned.
More details can be found in the spec for the css height property, but essentially, #inner
must ignore #outer
height if #outer
's height is auto
, unless #outer
is positioned absolutely. Then #inner
height will be 0, unless #inner
itself is positioned absolutely.
<style>
#outer {
position:absolute;
height:auto; width:200px;
border: 1px solid red;
}
#inner {
position:absolute;
height:100%;
width:20px;
border: 1px solid black;
}
</style>
<div id='outer'>
<div id='inner'>
</div>
text
</div>
However... By positioning #inner
absolutely, a float
setting will be ignored, so you will need to choose a width for #inner
explicitly, and add padding in #outer
to fake the text wrapping I suspect you want. For example, below, the padding of #outer
is the width of #inner
+3. Conveniently (as the whole point was to get #inner
height to 100%) there's no need to wrap text beneath #inner
, so this will look just like #inner
is floated.
<style>
#outer2{
padding-left: 23px;
position:absolute;
height:auto;
width:200px;
border: 1px solid red;
}
#inner2{
left:0;
position:absolute;
height:100%;
width:20px;
border: 1px solid black;
}
</style>
<div id='outer2'>
<div id='inner2'>
</div>
text
</div>
I deleted my previous answer, as it was based on too many wrong assumptions about your goal.
Nevermind found an answer. Ty the same for anyone who was willing to reply.
WHERE DATEDIFF(mydata,'2008-11-20') >=0;
make sure to change in ajax call
async: true,
type: "GET",
dataType: "html",
Have you tried the validates_date_time
plug-in?
The transform CSS property lets you rotate, scale, skew, or translate an element.
So you can easily use the transform: scale(2.5);
option to scale 2.5 times for example.
change svg
to match your element
function svg2img(){
var svg = document.querySelector('svg');
var xml = new XMLSerializer().serializeToString(svg);
var svg64 = btoa(xml); //for utf8: btoa(unescape(encodeURIComponent(xml)))
var b64start = 'data:image/svg+xml;base64,';
var image64 = b64start + svg64;
return image64;
};svg2img()
This is working for me, you might change your code like this
var responseData=x.toString();
to
var responseData=x.toString("binary");
and finally
response.write(new Buffer(toTransmit, "binary"));
Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable
Type in command line
echo %JAVA_HOME%
and
java -version
To verify whether your installation was done successfully.
This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.
Steps to resolve:
Open the Run window:
Press windows+R
Open registry window:
Type regedit
and enter.
Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\
If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.
For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:
Create a new subkey of 1.8.
For 1.8 create a String Key with name JavaHome with the value of JRE home:
Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html
This is a very late answer,but this might help.I went to this link and searched for ojdbc8(I was trying to add jdbc oracle driver) When clicked on the result , a note was displayed like this:
I clicked the link in the note and the correct dependency was mentioned like below
If you know the arrays are of the same size it is provably faster to sort then compare
Arrays.sort(array1)
Arrays.sort(array2)
return Arrays.equals(array1, array2)
If you do not want to change the order of the data in the arrays then do a System.arraycopy
first.
You can use Microsoft's row_number() function to decide which rows to return. That means that you aren't limited to just the top X results, you can take pages.
SELECT *
FROM (SELECT row_number() over (order by UserID) AS line_no, *
FROM dbo.User) as users
WHERE users.line_no < 10
OR users.line_no BETWEEN 34 and 67
You have to nest the original query though, because otherwise you'll get an error message telling you that you can't do what you want to in the way you probably should be able to in an ideal world.
Msg 4108, Level 15, State 1, Line 3
Windowed functions can only appear in the SELECT or ORDER BY clauses.
This worked for me:
[XmlInclude(typeof(BankPayment))]
[Serializable]
public abstract class Payment { }
[Serializable]
public class BankPayment : Payment {}
[Serializable]
public class Payments : List<Payment>{}
XmlSerializer serializer = new XmlSerializer(typeof(Payments), new Type[]{typeof(Payment)});
If the caller is another project, you should write the config in caller project not the called one.
I think you should add style="background:white;" to make looks like it is writable
<input type="text" size="23" name="dateMonthly" id="dateMonthly" readonly="readonly" style="background:white;"/>
SQLLite requires dates to be in YYYY-MM-DD
format. Since the data in your database and the string in your query isn't in that format, it is probably treating your "dates" as strings.
After reading the posts above, I decided to use this code:
itemModel.findOne({'pid':obj.pid},function(e,r){
if(r!=null)
{
itemModel.update({'pid':obj.pid},obj,{upsert:true},cb);
}
else
{
var item=new itemModel(obj);
item.save(cb);
}
});
if r is null, we create new item. Otherwise, use upsert in update because update does not create new item.
I can see that this only for actually turning the dialogs back on. But if you are a web dev and you would like to see a way to possibly have some form of notification when these are off...in the case that you are using native alerts/confirms for validation or whatever. Check this solution to detect and notify the user https://stackoverflow.com/a/23697435/1248536
Use the deployment Toolkit's deployJava.js (though this ensures a minimum version, rather than a specific version)
Port 4200 is already in use. Use '--port' to specify a different port
This means that you already have another service running on port 4200. If this is the case
you can either . shut down the other service. use the --port
flag when running ng
serve like this:
ng serve --port 9001
Another thing to notice is that, on some machines, the domain localhost may not work. You may see a set of numbers such as 127.0.0.1. When you run ng serve it should show you what URL the server is running on, so be sure to read the messages on your machine to find your exact development URL.
In the MSDN blog post Many Questions: switch on type is some information on why .NET does not provide switching on types.
As usual - workarounds always exists.
This one isn't mine, but unfortunately I have lost the source. It makes switching on types possible, but I personally think it's quite awkward (the dictionary idea is better):
public class Switch
{
public Switch(Object o)
{
Object = o;
}
public Object Object { get; private set; }
}
/// <summary>
/// Extensions, because otherwise casing fails on Switch==null
/// </summary>
public static class SwitchExtensions
{
public static Switch Case<T>(this Switch s, Action<T> a)
where T : class
{
return Case(s, o => true, a, false);
}
public static Switch Case<T>(this Switch s, Action<T> a,
bool fallThrough) where T : class
{
return Case(s, o => true, a, fallThrough);
}
public static Switch Case<T>(this Switch s,
Func<T, bool> c, Action<T> a) where T : class
{
return Case(s, c, a, false);
}
public static Switch Case<T>(this Switch s,
Func<T, bool> c, Action<T> a, bool fallThrough) where T : class
{
if (s == null)
{
return null;
}
T t = s.Object as T;
if (t != null)
{
if (c(t))
{
a(t);
return fallThrough ? s : null;
}
}
return s;
}
}
Usage:
new Switch(foo)
.Case<Fizz>
(action => { doingSomething = FirstMethodCall(); })
.Case<Buzz>
(action => { return false; })
One line of jQuery does it all!
$("#myCombobox option[text='it\'s me']").attr("selected","selected");