I don't think you can use braces.
According to the Bash manual about case in Conditional Constructs.
Each pattern undergoes tilde expansion, parameter expansion, command substitution, and arithmetic expansion.
Nothing about Brace Expansion unfortunately.
So you'd have to do something like this:
case $1 in
req*)
...
;;
met*|meet*)
...
;;
*)
# You should have a default one too.
esac
In ES6, you can do like this.
var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print Object { name="John"}
var key = "name";_x000D_
var person = {[key]:"John"};_x000D_
console.log(person); // should print Object { name="John"}
_x000D_
Its called Computed Property Names, its implemented using bracket notation( square brackets) []
Example: { [variableName] : someValue }
Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed and used as the property name.
For ES5, try something like this
var yourObject = {};
yourObject[yourKey] = "yourValue";
console.log(yourObject );
example:
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
var person = {};_x000D_
var key = "name";_x000D_
_x000D_
person[key] /* this is same as person.name */ = "John";_x000D_
_x000D_
console.log(person); // should print Object { name="John"}
_x000D_
I think the easiest way is through the collections module.
import collections
FinanceCtaCteM = collections.namedtuple('FinanceCtaCte', 'forma_pago doc_pago get_total')
def get_total(): return 98989898
financtacteobj = FinanceCtaCteM(forma_pago='CONTADO', doc_pago='EFECTIVO',
get_total=get_total)
print financtacteobj.get_total()
print financtacteobj.forma_pago
print financtacteobj.doc_pago
If it is a simple py script refer here
Else for GUI :
$ pip3 install cx_Freeze
1) Create a setup.py file and put in the same directory as of the .py file you want to convert.
2)Copy paste the following lines in the setup.py and do change the "filename.py" into the filename you specified.
from cx_Freeze import setup, Executable
setup(
name="GUI PROGRAM",
version="0.1",
description="MyEXE",
executables=[Executable("filename.py", base="Win32GUI")],
)
3) Run the setup.py "$python setup.py build"
4)A new directory will be there there called "build". Inside it you will get your .exe file to be ready to launced directly. (Make sure you copy paste the images files and other external files into the build directory)
CERAS is a class name which cannot be assigned. As the class implements IDisposable a typical usage would be:
using (CERas.CERAS ceras = new CERas.CERAS())
{
// call some method on ceras
}
im use this code to and suggest you:
1) sudo sed -i -e 's|disco|eoan|g' /etc/apt/sources.list
2) sudo apt update
If they are two integers you can try a quick and dirty trick: Map<String, ?>
using the key as i+"#"+j
.
If the key i+"#"+j
is the same as j+"#"+i
try min(i,j)+"#"+max(i,j)
.
Mathias Bynens has compiled a list of well-known URL regexes with test URLs. There is little reason to write a new regular expression; just pick an existing one that suits you best.
But the comparison table for those regexes also shows that it is next to impossible to do URL validation with a single regular expression. All of the regexes in Bynens' list produce false positives and false negatives.
I suggest that you use an existing URL parser (for example new URL('http://www.example.com/')
in JavaScript) and then apply the checks you want to perform against the parsed and normalized form of the URL resp. its components. Using the JavaScript URL
interface has the additional benefit that it will only accept such URLs that are really accepted by the browser.
You should also keep in mind that technically incorrect URLs may still work. For example http://w_w_w.example.com/
, http://www..example.com/
, http://123.example.com/
all have an invalid hostname part but every browser I know will try to open them without complaints, and when you specify IP addresses for those invalid names in /etc/hosts/
such URLs will even work but only on your computer.
The question is, therefore, not so much whether a URL is valid, but rather which URLs work and should be allowed in a particular context.
If you want to do URL validation there are a lot of details and edge cases that are easy to overlook:
http://user:[email protected]/
.http://www.stackoverflow.com.
). [-0-9a-zA-z]
is definitely no longer sufficient.co.uk
and many others).Which of these limitations and rules apply is a question of project requirements and taste.
I have recently written a URL validator for a web app that is suitable for user-supplied URLs in forums, social networks, or the like. Feel free to use it as a base for your own one:
I have also written a blog post The Gory Details of URL Validation with more in-depth information.
With redis-cli
:
FLUSHDB - Removes data from your connection's CURRENT database.
FLUSHALL - Removes data from ALL databases.
A TINYINT is an 8-bit integer value, a BIT field can store between 1 bit, BIT(1), and 64 bits, BIT(64). For a boolean values, BIT(1) is pretty common.
Use Immersive Full-Screen Mode
call fullScreen()
on ImageView
click.
public void fullScreen() {
// BEGIN_INCLUDE (get_current_ui_flags)
// The UI options currently enabled are represented by a bitfield.
// getSystemUiVisibility() gives us that bitfield.
int uiOptions = getWindow().getDecorView().getSystemUiVisibility();
int newUiOptions = uiOptions;
// END_INCLUDE (get_current_ui_flags)
// BEGIN_INCLUDE (toggle_ui_flags)
boolean isImmersiveModeEnabled =
((uiOptions | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) == uiOptions);
if (isImmersiveModeEnabled) {
Log.i(TAG, "Turning immersive mode mode off. ");
} else {
Log.i(TAG, "Turning immersive mode mode on.");
}
// Navigation bar hiding: Backwards compatible to ICS.
if (Build.VERSION.SDK_INT >= 14) {
newUiOptions ^= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
}
// Status bar hiding: Backwards compatible to Jellybean
if (Build.VERSION.SDK_INT >= 16) {
newUiOptions ^= View.SYSTEM_UI_FLAG_FULLSCREEN;
}
// Immersive mode: Backward compatible to KitKat.
// Note that this flag doesn't do anything by itself, it only augments the behavior
// of HIDE_NAVIGATION and FLAG_FULLSCREEN. For the purposes of this sample
// all three flags are being toggled together.
// Note that there are two immersive mode UI flags, one of which is referred to as "sticky".
// Sticky immersive mode differs in that it makes the navigation and status bars
// semi-transparent, and the UI flag does not get cleared when the user interacts with
// the screen.
if (Build.VERSION.SDK_INT >= 18) {
newUiOptions ^= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
}
getWindow().getDecorView().setSystemUiVisibility(newUiOptions);
//END_INCLUDE (set_ui_flags)
}
Read more
Example Download
Don't bother, the default calculation is really good and suffice for 99,9999% of the cases. And if you run into problems, you can - as already stated - introduce UID's as the need arrise (which is highly unlikely)
Like this add position:fixed;
and bottom:0;
below the selector #footer
:
CSS
#footer {
background-color: #F3F3F3;
padding-top: 10px;
padding-bottom: 0px;
position:fixed;
bottom:0;
width:100%;
}
I know this is too old, but, just i case someone gets to this question from Google now, you can install it by typing apt-get install phantomjs
I love Charles.
The free version works fine for me.
Throttling, rerwiting, breakpoints are all awesome features.
Change Minute parameter to 0.
You can set the cron for every three hours as:
0 */3 * * * your command here ..
Python 2.6 and 3 specifically say to avoid using PIPE for stdout and stderr.
The correct way is
import subprocess
# must create a file object to store the output. Here we are getting
# the ssid we are connected to
outfile = open('/tmp/ssid', 'w');
status = subprocess.Popen(["iwgetid"], bufsize=0, stdout=outfile)
outfile.close()
# now operate on the file
you can set maxlength with jquery which is very fast
jQuery(document).ready(function($){ //fire on DOM ready
setformfieldsize(jQuery('#comment'), 50, 'charsremain')
})
This is a quick efficient one:
bool isPrimeNumber(int n) {
int divider = 2;
while (n % divider != 0) {
divider++;
}
if (n == divider) {
return true;
}
else {
return false;
}
}
It will start finding a divisible number of n, starting by 2. As soon as it finds one, if that number is equal to n then it's prime, otherwise it's not.
The listFiles
method, with or without a filter does not guarantee any order.
It does, however, return an array, which you can sort with Arrays.sort()
.
File[] files = XMLDirectory.listFiles(filter_xml_files);
Arrays.sort(files);
for(File _xml_file : files) {
...
}
This works because File
is a comparable class, which by default sorts pathnames lexicographically. If you want to sort them differently, you can define your own comparator.
If you prefer using Streams:
A more modern approach is the following. To print the names of all files in a given directory, in alphabetical order, do:
Files.list(Paths.get(dirName)).sorted().forEach(System.out::println)
Replace the System.out::println
with whatever you want to do with the file names. If you want only filenames that end with "xml"
just do:
Files.list(Paths.get(dirName))
.filter(s -> s.toString().endsWith(".xml"))
.sorted()
.forEach(System.out::println)
Again, replace the printing with whichever processing operation you would like.
remote show
shows all the branches on the remote, including those that are not tracked locally and even those that have not yet been fetched.
git remote show <remote-name>
It also tries to show the status of the branches relative to your local repository:
> git remote show origin
* remote origin
Fetch URL: C:/git/.\remote_repo.git
Push URL: C:/git/.\remote_repo.git
HEAD branch: master
Remote branches:
branch_that_is_not_even_fetched new (next fetch will store in remotes/origin)
branch_that_is_not_tracked tracked
branch_that_is_tracked tracked
master tracked
Local branches configured for 'git pull':
branch_that_is_tracked merges with remote branch_that_is_tracked
master merges with remote master
Local refs configured for 'git push':
branch_that_is_tracked pushes to branch_that_is_tracked (fast-forwardable)
master pushes to master (up to date)
Timer is another way to do your work but be quiet sure to add runOnUiThread
if you are working with UI.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity {
CheckBox optSingleShot;
Button btnStart, btnCancel;
TextView textCounter;
Timer timer;
MyTimerTask myTimerTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
optSingleShot = (CheckBox)findViewById(R.id.singleshot);
btnStart = (Button)findViewById(R.id.start);
btnCancel = (Button)findViewById(R.id.cancel);
textCounter = (TextView)findViewById(R.id.counter);
btnStart.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
if(timer != null){
timer.cancel();
}
//re-schedule timer here
//otherwise, IllegalStateException of
//"TimerTask is scheduled already"
//will be thrown
timer = new Timer();
myTimerTask = new MyTimerTask();
if(optSingleShot.isChecked()){
//singleshot delay 1000 ms
timer.schedule(myTimerTask, 1000);
}else{
//delay 1000ms, repeat in 5000ms
timer.schedule(myTimerTask, 1000, 5000);
}
}});
btnCancel.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
if (timer!=null){
timer.cancel();
timer = null;
}
}
});
}
class MyTimerTask extends TimerTask {
@Override
public void run() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
final String strDate = simpleDateFormat.format(calendar.getTime());
runOnUiThread(new Runnable(){
@Override
public void run() {
textCounter.setText(strDate);
}});
}
}
}
and xml is...
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://android-er.blogspot.com/"
android:textStyle="bold" />
<CheckBox
android:id="@+id/singleshot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Single Shot"/>
Another Way to use CountDownTimer
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
Schedule a countdown until a time in the future, with regular notifications on intervals along the way. Example of showing a 30 second countdown in a text field:
Edit your conftest.py and add following lines of code:
import os, sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(file), '..')))
And if trying to run the test case through terminal, use following ex:
python -m pytest test_some_step_file_steps.py --html=HTML_step_file_output.html --self-contained-html
if you are using html agility pack use getattributeValue:
$doc2.DocumentNode.SelectNodes("//div[@class='className']/div[@class='InternalClass']/a[@class='InternalClass']").GetAttributeValue("href","")
Update: 19 -11-2019
The below answer is no more relevant to present day.
So for any one looking for answers you should look at the documentation linked below
https://developer.android.com/training/articles/user-data-ids
Old Answer - Not relevant now. You check this blog in the link below
http://android-developers.blogspot.in/2011/03/identifying-app-installations.html
ANDROID_ID
import android.provider.Settings.Secure;
private String android_id = Secure.getString(getContext().getContentResolver(),
Secure.ANDROID_ID);
The above is from the link @ Is there a unique Android device ID?
More specifically, Settings.Secure.ANDROID_ID. This is a 64-bit quantity that is generated and stored when the device first boots. It is reset when the device is wiped.
ANDROID_ID seems a good choice for a unique device identifier. There are downsides: First, it is not 100% reliable on releases of Android prior to 2.2 (“Froyo”). Also, there has been at least one widely-observed bug in a popular handset from a major manufacturer, where every instance has the same ANDROID_ID.
The below solution is not a good one coz the value survives device wipes (“Factory resets”) and thus you could end up making a nasty mistake when one of your customers wipes their device and passes it on to another person.
You get the imei number of the device using the below
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.getDeviceId();
http://developer.android.com/reference/android/telephony/TelephonyManager.html#getDeviceId%28%29
Add this is manifest
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
You are using some sort of revision control, right? Then it should be quite simple to restore to the commit before you added the gem, or revert the one where you added it if you have several revisions after that you wish to keep.
Because someone asked for the Data.Table version of this, and because the given data.frame solution does not work with data.table, I am providing the solution below.
Basically, use the :=
operator --> DT[x == 0, x := NA]
library("data.table")
status = as.data.table(occupationalStatus)
head(status, 10)
origin destination N
1: 1 1 50
2: 2 1 16
3: 3 1 12
4: 4 1 11
5: 5 1 2
6: 6 1 12
7: 7 1 0
8: 8 1 0
9: 1 2 19
10: 2 2 40
status[N == 0, N := NA]
head(status, 10)
origin destination N
1: 1 1 50
2: 2 1 16
3: 3 1 12
4: 4 1 11
5: 5 1 2
6: 6 1 12
7: 7 1 NA
8: 8 1 NA
9: 1 2 19
10: 2 2 40
Just use
document.getElementById('submitbutton').disabled = !cansubmit;
instead of the the if-clause that works only one-way.
Also, for the users who have JS disabled, I'd suggest to set the initial disabled
by JS only. To do so, just move the script behind the <form>
and call checkform();
once.
I wrote a simple Xcode 6 project that shows how to mix C++, Objective-C and Swift code:
https://github.com/romitagl/shared/tree/master/C-ObjC-Swift/Performance_Console
In particular, the example calls an Objective-C and a C++ function from the Swift.
The key is to create a shared header, Project-Bridging-Header.h, and put the Objective-C headers there.
Please download the project as a complete example.
Excellent answer! I do have a small addition. Regarding this solution:
TypedQuery<CustomObject> typedQuery = em.createQuery(query , String query = "SELECT NEW CustomObject(i.firstProperty, i.secondProperty) FROM ObjectName i WHERE i.id=100";
TypedQuery<CustomObject> typedQuery = em.createQuery(query , CustomObject.class);
List<CustomObject> results = typedQuery.getResultList();CustomObject.class);
To prevent a class not found error simply insert the full package name. Assuming org.company.directory is the package name of CustomObject:
String query = "SELECT NEW org.company.directory.CustomObject(i.firstProperty, i.secondProperty) FROM ObjectName i WHERE i.id=10";
TypedQuery<CustomObject> typedQuery = em.createQuery(query , CustomObject.class);
List<CustomObject> results = typedQuery.getResultList();
Use the -p flag and add /udp
suffix to the port number.
-p 53160:53160/udp
Full command
sudo docker run -p 53160:53160 \
-p 53160:53160/udp -p 58846:58846 \
-p 8112:8112 -t -i aostanin/deluge /start.sh
If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.
You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile
(EXPOSE does not publish the port):
EXPOSE 8285/udp
Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)
The idea ...To create a File object (api) in javaScript for images already present in the DOM :
<img src="../img/Products/fijRKjhudDjiokDhg1524164151.jpg">
var file = new File(['fijRKjhudDjiokDhg1524164151'],
'../img/Products/fijRKjhudDjiokDhg1524164151.jpg',
{type:'image/jpg'});
// created object file
console.log(file);
Don't do that ! ... (but I did it anyway)
-> the console give a result similar as an Object File :
File(0) {name: "fijRKjokDhgfsKtG1527053050.jpg", lastModified: 1527053530715, lastModifiedDate: Wed May 23 2018 07:32:10 GMT+0200 (Paris, Madrid (heure d’été)), webkitRelativePath: "", size: 0, …}
lastModified:1527053530715
lastModifiedDate:Wed May 23 2018 07:32:10 GMT+0200 (Paris, Madrid (heure d’été)) {}
name:"fijRKjokDhgfsKtG1527053050.jpg"
size:0
type:"image/jpg"
webkitRelativePath:""__proto__:File
But the size of the object is wrong ...
Why i need to do that ?
For example to retransmit an image form already uploaded, during a product update, along with additional images added during the update
No need to embed! Just simply send the user to google and add the var in the search like this: (Remember, code might not work on this, so try in a browser if it doesn't.) Hope it works!
<textarea id="Blah"></textarea><button onclick="search()">Search</button>
<script>
function search() {
var Blah = document.getElementById("Blah").value;
location.replace("https://www.google.com/search?q=" + Blah + "");
}
</script>
function search() {_x000D_
var Blah = document.getElementById("Blah").value;_x000D_
location.replace("https://www.google.com/search?q=" + Blah + "");_x000D_
}
_x000D_
<textarea id="Blah"></textarea><button onclick="search()">Search</button>
_x000D_
No, @Controller
is not the same as @Service
, although they both are specializations of @Component
, making them both candidates for discovery by classpath scanning. The @Service
annotation is used in your service layer, and @Controller
is for Spring MVC controllers in your presentation layer. A @Controller
typically would have a URL mapping and be triggered by a web request.
You have to delete Your appname.dll file from your output folder. Cleanup Debug and Release folders. Rebuild and copy to output folder regenerated dll file.
IEnumerable<string> e = (from char c in source
select new { Data = c.ToString() }).Select(t = > t.Data);
// or
IEnumerable<string> e = from char c in source
select c.ToString();
// or
IEnumerable<string> e = source.Select(c = > c.ToString());
Then you can call ToList()
:
List<string> l = (from char c in source
select new { Data = c.ToString() }).Select(t = > t.Data).ToList();
// or
List<string> l = (from char c in source
select c.ToString()).ToList();
// or
List<string> l = source.Select(c = > c.ToString()).ToList();
To switch the display-style between block
and none
you can do something like this:
function toggleDiv(id) {
var div = document.getElementById(id);
div.style.display = div.style.display == "none" ? "block" : "none";
}
working demo: http://jsfiddle.net/BQUyT/2/
public static void showPyramid(int level)
{
for(int i=0;i<level;i++)
{
for(int j=0;j<level-i-1;j++)
{
System.out.print(" ");
}
for(int k=level-i;k<=level;k++)
{
System.out.print("*");
}
for(int k=level-i;k<level;k++)
{
System.out.print("*");
}
for(int j=0;j<level-i;j++)
{
System.out.print(" ");
}
System.out.print("\n");
}
}
Output
*
***
*****
*******
*********
***********
div{
border-left:solid red 3px;
border-right:solid violet 4px;
border-top:solid blue 4px;
border-bottom:solid green 4px;
background:grey;
width:100px; height:50px
}
Spring MVC runs on top of the Servlet API. So, you can use HttpServletRequest#getParameter()
for this:
String value1 = request.getParameter("value1");
String value2 = request.getParameter("value2");
The HttpServletRequest
should already be available to you inside Spring MVC as one of the method arguments of the handleRequest()
method.
List is an Interface . You cant use List to initialize it.
List<String> supplierNames = new ArrayList<String>();
These are the some of List impelemented classes,
ArrayList, LinkedList, Vector
You could use any of this as per your requirement. These each classes have its own features.
Use an interval instead of an integer:
SELECT *
FROM table
WHERE auth_user.lastactivity > CURRENT_TIMESTAMP - INTERVAL '100 days'
If you interested in running Entity Framework with MySql on mono/linux/macos, this might be helpful https://iyalovoi.wordpress.com/2015/04/06/entity-framework-with-mysql-on-mac-os/
Below code is used in my application to send email with an attachment here the attachments is an image .You can send any type of file only thing is to keep in mind is that you had to specify the correct 'mimeType'
add this to your .h file
#import <MessageUI/MFMailComposeViewController.h>
Add MessageUI.framework to your project file
NSArray *paths = SSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:@"myGreenCard.png"];
MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:@"Green card application"];
[controller setMessageBody:@"Hi , <br/> This is my new latest designed green card." isHTML:YES];
[controller addAttachmentData:[NSData dataWithContentsOfFile:getImagePath] mimeType:@"png" fileName:@"My Green Card"];
if (controller)
[self presentModalViewController:controller animated:YES];
[controller release];
Delegate method is as shown below
-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error;
{
if (result == MFMailComposeResultSent) {
NSLog(@"It's away!");
}
[self dismissModalViewControllerAnimated:YES];
}
This is not the exact answer for your question, but this may help you
public class JsonParser {
private static DefaultHttpClient httpClient = ConnectionManager.getClient();
public static List<Club> getNearestClubs(double lat, double lon) {
// YOUR URL GOES HERE
String getUrl = Constants.BASE_URL + String.format("getClosestClubs?lat=%f&lon=%f", lat, lon);
List<Club> ret = new ArrayList<Club>();
HttpResponse response = null;
HttpGet getMethod = new HttpGet(getUrl);
try {
response = httpClient.execute(getMethod);
// CONVERT RESPONSE TO STRING
String result = EntityUtils.toString(response.getEntity());
// CONVERT RESPONSE STRING TO JSON ARRAY
JSONArray ja = new JSONArray(result);
// ITERATE THROUGH AND RETRIEVE CLUB FIELDS
int n = ja.length();
for (int i = 0; i < n; i++) {
// GET INDIVIDUAL JSON OBJECT FROM JSON ARRAY
JSONObject jo = ja.getJSONObject(i);
// RETRIEVE EACH JSON OBJECT'S FIELDS
long id = jo.getLong("id");
String name = jo.getString("name");
String address = jo.getString("address");
String country = jo.getString("country");
String zip = jo.getString("zip");
double clat = jo.getDouble("lat");
double clon = jo.getDouble("lon");
String url = jo.getString("url");
String number = jo.getString("number");
// CONVERT DATA FIELDS TO CLUB OBJECT
Club c = new Club(id, name, address, country, zip, clat, clon, url, number);
ret.add(c);
}
} catch (Exception e) {
e.printStackTrace();
}
// RETURN LIST OF CLUBS
return ret;
}
}
Again, it’s relatively straight forward, but the methods I’ll make special note of are:
JSONArray ja = new JSONArray(result);
JSONObject jo = ja.getJSONObject(i);
long id = jo.getLong("id");
String name = jo.getString("name");
double clat = jo.getDouble("lat");
It's easier to do this:
driver.findElements(By.linkText("myLinkText")).size() < 1
The thing of it is there are 2 main protocol versions of WebSockets in use today. The old version which uses the [0x00][message][0xFF]
protocol, and then there's the new version using Hybi formatted packets.
The old protocol version is used by Opera and iPod/iPad/iPhones so it's actually important that backward compatibility is implemented in WebSockets servers. With these browsers using the old protocol, I discovered that refreshing the page, or navigating away from the page, or closing the browser, all result in the browser automatically closing the connection. Great!!
However with browsers using the new protocol version (eg. Firefox, Chrome and eventually IE10), only closing the browser will result in the browser automatically closing the connection. That is to say, if you refresh the page, or navigate away from the page, the browser does NOT automatically close the connection. However, what the browser does do, is send a hybi packet to the server with the first byte (the proto ident) being 0x88
(better known as the close data frame). Once the server receives this packet it can forcefully close the connection itself, if you so choose.
This is the easiest way I can figure out:
#!/usr/bin/python3
for i in range(97, 123):
print("{:c}".format(i), end='')
So, 97 to 122 are the ASCII number equivalent to 'a' to and 'z'. Notice the lowercase and the need to put 123, since it will not be included).
In print function make sure to set the {:c}
(character) format, and, in this case, we want it to print it all together not even letting a new line at the end, so end=''
would do the job.
The result is this:
abcdefghijklmnopqrstuvwxyz
One thing that I found quite helpful to use to print all images :
_, axs = plt.subplots(n_row, n_col, figsize=(12, 12))
axs = axs.flatten()
for img, ax in zip(imgs, axs):
ax.imshow(img)
plt.show()
Or how about this?
with some_birthdays as
(
select date '1968-06-09' d from dual union all
select date '1970-06-10' from dual union all
select date '1972-06-11' from dual union all
select date '1974-12-11' from dual union all
select date '1976-09-17' from dual
)
select trunc(sysdate) today
, d birth_date
, floor(months_between(trunc(sysdate),d)/12) age
from some_birthdays;
Add jQuery JavaScript library together with the jquery.zbox.css and jquery.zbox.js to your webpage.
<link rel="stylesheet" href="jquery.zbox.css">
<script src="jquery.min.js"></script>
<script src="jquery.zbox.min.js"></script>
Add a group of thumbnails with links pointing to the full sized images into the webpage.
<a class="zb" rel="group" href="1.png" title="Image 1">
<img src="thumb1.png">
</a>
<a class="zb" rel="group" href="2.png" title="Image 2">
<img src="thumb2.png">
</a>
<a class="zb" rel="group" href="3.png" title="Image 3">
<img src="thumb3.png">
</a>
Call the function on document ready. That's it.
In the view source do:
$(".zb").zbox();
For an associative array you can just use merge.
$arr = array('item2', 'item3', 'item4');
$arr = array_merge(array('item1'), $arr)
Sounds like you're trying to execute the PHP code directly in your shell. Your shell doesn't speak PHP, so it interprets your PHP code as though it's in your shell's native language, as though you had literally run <?php
at the command line.
Shell scripts usually start with a "shebang" line that tells the shell what program to use to interpret the file. Begin your file like this:
#!/usr/bin/env php
<?php
//Connection
function connection () {
Besides that, the string you're passing to exec
doesn't make any sense. It starts with a slash all by itself, it uses too many periods in the path, and it has a stray right parenthesis.
Copy the contents of the command string and paste them at your command line. If it doesn't run there, then exec
probably won't be able to run it, either.
Another option is to change the command you execute. Instead of running the script directly, run php
and pass your script as an argument. Then you shouldn't need the shebang line.
exec('php name.php');
select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)
select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)
should works
If you also get the key, you can delete that item like this:
foreach ($display_related_tags as $key => $tag_name) {
if($tag_name == $found_tag['name']) {
unset($display_related_tags[$key]);
}
}
SELECT CONVERT(nvarchar(6), GETDATE(), 112)
Note that if you still want to exclude a set, including things like slashes and special characters you can do the following:
var outString = sourceString.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');
take special note that in order to also include the "minus" character, you need to escape it with a backslash like the latter group. if you don't it will also select 0-9 which is probably undesired.
based on examples above and examples found on other sites, I created a generic procedure and some examples.
'Simple helper procedure to create a dropdown in a cell based on a list of values in a range
'ValueSheetName : the name of the sheet containing the value range
'ValueRangeString : the range on the sheet with name ValueSheetName containing the values for the dropdown
'CreateOnSheetName : the name of the sheet where the dropdown needs to be created
'CreateInRangeString : the range where the dropdown needs to be created
'FieldName As String : a name of the dropdown, will be used in the inputMessage and ErrorMessage
'See example below ExampleCreateDropDown
Public Sub CreateDropDown(ValueSheetName As String, ValueRangeString As String, CreateOnSheetName As String, CreateInRangeString As String, FieldName As String)
Dim ValueSheet As Worksheet
Set ValueSheet = Worksheets(ValueSheetName) 'The sheet containing the values
Dim ValueRange As Range: Set ValueRange = ValueSheet.Range(ValueRangeString) 'The range containing the values
Dim CreateOnSheet As Worksheet
Set CreateOnSheet = Worksheets(CreateOnSheetName) 'The sheet containing the values
Dim CreateInRange As Range: Set CreateInRange = CreateOnSheet.Range(CreateInRangeString)
Dim InputTitle As String: InputTitle = "Please Select a Value"
Dim InputMessage As String: InputMessage = "for " & FieldName
Dim ErrorTitle As String: ErrorTitle = "Please Select a Value"
Dim ErrorMessage As String: ErrorMessage = "for " & FieldName
Dim ShowInput As Boolean: ShowInput = True 'Show input message on hover
Dim ShowError As Boolean: ShowError = True 'Show error message on error
Dim ValidationType As XlDVType: ValidationType = xlValidateList
Dim ValidationAlertStyle As XlDVAlertStyle: ValidationAlertStyle = xlValidAlertStop 'Stop on invalid value
Dim ValidationOperator As XlFormatConditionOperator: ValidationOperator = xlEqual 'Value must be equal to one of the Values from the ValidationFormula1
Dim ValidationFormula1 As Variant: ValidationFormula1 = "=" & ValueSheetName & "!" & ValueRange.Address 'Formula referencing the values from the ValueRange
Dim ValidationFormula2 As Variant: ValidationFormula2 = ""
Call CreateDropDownWithValidationInCell(CreateInRange, InputTitle, InputMessage, ErrorTitle, ErrorMessage, ShowInput, ShowError, ValidationType, ValidationAlertStyle, ValidationOperator, ValidationFormula1, ValidationFormula2)
End Sub
'An example using the ExampleCreateDropDown
Private Sub ExampleCreateDropDown()
Call CreateDropDown(ValueSheetName:="Test", ValueRangeString:="C1:C5", CreateOnSheetName:="Test", CreateInRangeString:="B1", FieldName:="test2")
End Sub
'The full option function if you need more configurable options
'To create a dropdown in a cell based on a list of values in a range
'Validation: https://msdn.microsoft.com/en-us/library/office/ff840078.aspx
'ValidationTypes: XlDVType https://msdn.microsoft.com/en-us/library/office/ff840715.aspx
'ValidationAlertStyle: XlDVAlertStyle https://msdn.microsoft.com/en-us/library/office/ff841223.aspx
'XlFormatConditionOperator https://msdn.microsoft.com/en-us/library/office/ff840923.aspx
'See example below ExampleCreateDropDownWithValidationInCell
Public Sub CreateDropDownWithValidationInCell(CreateInRange As Range, _
Optional InputTitle As String = "", _
Optional InputMessage As String = "", _
Optional ErrorTitle As String = "", _
Optional ErrorMessage As String = "", _
Optional ShowInput As Boolean = True, _
Optional ShowError As Boolean = True, _
Optional ValidationType As XlDVType = xlValidateList, _
Optional ValidationAlertStyle As XlDVAlertStyle = xlValidAlertStop, _
Optional ValidationOperator As XlFormatConditionOperator = xlEqual, _
Optional ValidationFormula1 As Variant = "", _
Optional ValidationFormula2 As Variant = "")
With CreateInRange.Validation
.Delete
.Add Type:=ValidationType, AlertStyle:=ValidationAlertStyle, Operator:=ValidationOperator, Formula1:=ValidationFormula1, Formula2:=ValidationFormula2
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = InputTitle
.ErrorTitle = ErrorTitle
.InputMessage = InputMessage
.ErrorMessage = ErrorMessage
.ShowInput = ShowInput
.ShowError = ShowError
End With
End Sub
'An example using the CreateDropDownWithValidationInCell
Private Sub ExampleCreateDropDownWithValidationInCell()
Dim ValueSheetName As String: ValueSheetName = "Hidden" 'The sheet containing the values
Dim ValueRangeString As String: ValueRangeString = "C7:C9" 'The range containing the values
Dim CreateOnSheetName As String: CreateOnSheetName = "Test" 'The sheet containing the dropdown
Dim CreateInRangeString As String: CreateInRangeString = "A1" 'The range containing the dropdown
Dim ValueSheet As Worksheet
Set ValueSheet = Worksheets(ValueSheetName)
Dim ValueRange As Range: Set ValueRange = ValueSheet.Range(ValueRangeString)
Dim CreateOnSheet As Worksheet
Set CreateOnSheet = Worksheets(CreateOnSheetName)
Dim CreateInRange As Range: Set CreateInRange = CreateOnSheet.Range(CreateInRangeString)
Dim FieldName As String: FieldName = "Testing Dropdown"
Dim InputTitle As String: InputTitle = "Please Select a value"
Dim InputMessage As String: InputMessage = "for " & FieldName
Dim ErrorTitle As String: ErrorTitle = "Please Select a value"
Dim ErrorMessage As String: ErrorMessage = "for " & FieldName
Dim ShowInput As Boolean: ShowInput = True
Dim ShowError As Boolean: ShowError = True
Dim ValidationType As XlDVType: ValidationType = xlValidateList
Dim ValidationAlertStyle As XlDVAlertStyle: ValidationAlertStyle = xlValidAlertStop
Dim ValidationOperator As XlFormatConditionOperator: ValidationOperator = xlEqual
Dim ValidationFormula1 As Variant: ValidationFormula1 = "=" & ValueSheetName & "!" & ValueRange.Address
Dim ValidationFormula2 As Variant: ValidationFormula2 = ""
Call CreateDropDownWithValidationInCell(CreateInRange, InputTitle, InputMessage, ErrorTitle, ErrorMessage, ShowInput, ShowError, ValidationType, ValidationAlertStyle, ValidationOperator, ValidationFormula1, ValidationFormula2)
End Sub
Use this CSS hack, it saved me lot of trouble and time.
I use it in every project.
Below is a simple method to identify an empty string:
a="" #Empty string
if(len(a)==0): #len() is used to find the length of the string or variable inside its' brackets.
print("Empty")
else:
print("Filled")
The above len() method is an inbuilt function that helps us to find the length of a certain string or variable. It can also be used in the case of lists.
LOGIC: If the length of the character or variable is 0 then absolutely it means that the string or variable is empty. BUT remember that this will work only in the case of strings and lists and not with integers. Below is the code to find length of integers.
a=int(input())
if(len(str(a))==0):
print(True)
In the above code str() is used to convert an int to a string format like from 123 to its string format "123". In the string format it will be valid.
Just to clear some things up here. The answer that was accepted does not do the same as PHP in_array.
To do the same as PHP in_array use following expression:
{% if myVar in myArray %}
If you want to negate this you should use this:
{% if myVar not in myArray %}
At the beginning of your file you set raw_input
to 0. Do not do this, at it modifies the built-in raw_input()
function. Therefore, whenever you call raw_input()
, it is essentially calling 0()
, which raises the error. To remove the error, remove the first line of your code:
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54
def intro():
print("Welcome! This program will convert measures for you.")
main()
def main():
print("Select operation.")
print("1.Miles to Kilometers")
print("2.Fahrenheit to Celsius")
print("3.Gallons to liters")
print("4.Pounds to kilograms")
print("5.Inches to centimeters")
choice = input("Enter your choice by number: ")
if choice == '1':
convertMK()
elif choice == '2':
converCF()
elif choice == '3':
convertGL()
elif choice == '4':
convertPK()
elif choice == '5':
convertPK()
else:
print("Error")
def convertMK():
input_M = float(raw_input(("Miles: ")))
M_conv = (M) * input_M
print("Kilometers: %f\n" % M_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def converCF():
input_F = float(raw_input(("Fahrenheit: ")))
F_conv = (input_F - 32) * 5/9
print("Celcius: %f\n") % F_conv
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def convertGL():
input_G = float(raw_input(("Gallons: ")))
G_conv = input_G * 3.6
print("Centimeters: %f\n" % G_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertPK():
input_P = float(raw_input(("Pounds: ")))
P_conv = input_P * 0.45
print("Centimeters: %f\n" % P_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertIC():
input_cm = float(raw_input(("Inches: ")))
inches_conv = input_cm * 2.54
print("Centimeters: %f\n" % inches_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def end():
print("This program will close.")
exit()
intro()
R.color.black
or some color are obviously integers. It needs a RGB value. You can give your own like #FF123454
which represents various primary colors
Depending on what listeners you attach, trace output can go to the debug window, the console, a file, database, or all at once. The possibilities are literally endless, as implementing your own TraceListener is extremely simple.
If you are looking for a range of columns, you can try this:
df.iloc[7:] = df.iloc[7:].astype(float)
The examples above will convert type to be float, for all the columns begin with the 7th to the end. You of course can use different type or different range.
I think this is useful when you have a big range of columns to convert and a lot of rows. It doesn't make you go over each row by yourself - I believe numpy do it more efficiently.
This is useful only if you know that all the required columns contain numbers only - it will not change "bad values" (like string) to be NaN for you.
This is what I do, just add \n
and use encodeURIComponent
Example
var emailBody = "1st line.\n 2nd line \n 3rd line";
emailBody = encodeURIComponent(emailBody);
href = "mailto:[email protected]?body=" + emailBody;
Check encodeURIComponent docs
Try this
pd.set_option('display.height',1000)
pd.set_option('display.max_rows',500)
pd.set_option('display.max_columns',500)
pd.set_option('display.width',1000)
Here's another fun solution. This takes advantage of the locals()
dict of a comprehension, i.e. local variables generated inside the list comprehension scope:
>>> [locals().setdefault(i, (elem + locals().get(i-1, 0))) for i, elem
in enumerate(time_interval)]
[4, 10, 22]
Here's what the locals()
looks for each iteration:
>>> [[locals().setdefault(i, (elem + locals().get(i-1, 0))), locals().copy()][1]
for i, elem in enumerate(time_interval)]
[{'.0': <enumerate at 0x21f21f7fc80>, 'i': 0, 'elem': 4, 0: 4},
{'.0': <enumerate at 0x21f21f7fc80>, 'i': 1, 'elem': 6, 0: 4, 1: 10},
{'.0': <enumerate at 0x21f21f7fc80>, 'i': 2, 'elem': 12, 0: 4, 1: 10, 2: 22}]
Performance is not terrible for small lists:
>>> %timeit list(accumulate([4, 6, 12]))
387 ns ± 7.53 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> %timeit np.cumsum([4, 6, 12])
5.31 µs ± 67.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
>>> %timeit [locals().setdefault(i, (e + locals().get(i-1,0))) for i,e in enumerate(time_interval)]
1.57 µs ± 12 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
And obviously falls flat for larger lists.
>>> l = list(range(1_000_000))
>>> %timeit list(accumulate(l))
95.1 ms ± 5.22 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
>>> %timeit np.cumsum(l)
79.3 ms ± 1.07 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
>>> %timeit np.cumsum(l).tolist()
120 ms ± 1.23 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
>>> %timeit [locals().setdefault(i, (e + locals().get(i-1, 0))) for i, e in enumerate(l)]
660 ms ± 5.14 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Even though the method is ugly and not practical, it sure is fun.
With some HTML changes, you can absolutely achieve this with CSS:
Lorem ipsum dolor sit amet
<p id="textarea">
<!-- This is where I want to additional text-->
All that delicious text is in here!
</p>
<!-- the show/hide controls inside of the following
list, for ease of selecting with CSS -->
<ul class="controls">
<li class="show"><a href="#textarea">Show</a></li>
<li class="hide"><a href="#">Hide</a></li>
</ul>
<p>Here is some more text</p>
Coupled with the CSS:
#textarea {
display: none; /* hidden by default */
}
#textarea:target {
display: block; /* shown when a link targeting this id is clicked */
}
#textarea + ul.controls {
list-style-type: none; /* aesthetics only, adjust to taste, irrelevant to demo */
}
/* hiding the hide link when the #textarea is not targeted,
hiding the show link when it is selected: */
#textarea + ul.controls .hide,
#textarea:target + ul.controls .show {
display: none;
}
/* Showing the hide link when the #textarea is targeted,
showing the show link when it's not: */
#textarea:target + ul.controls .hide,
#textarea + ul.controls .show {
display: inline-block;
}
Or, you could use a label
and an input
of type="checkbox"
:
Lorem ipsum dolor sit amet
<input id="textAreaToggle" type="checkbox" />
<p id="textarea">
<!-- This is where I want to additional text-->
All that delicious text is in here!
</p>
<label for="textAreaToggle">textarea</label>
<p>Here is some more text</p>
With the CSS:
#textarea {
/* hide by default: */
display: none;
}
/* when the checkbox is checked, show the neighbouring #textarea element: */
#textAreaToggle:checked + #textarea {
display: block;
}
/* position the checkbox off-screen: */
input[type="checkbox"] {
position: absolute;
left: -1000px;
}
/* Aesthetics only, adjust to taste: */
label {
display: block;
}
/* when the checkbox is unchecked (its default state) show the text
'Show ' in the label element: */
#textAreaToggle + #textarea + label::before {
content: 'Show ';
}
/* when the checkbox is checked 'Hide ' in the label element; the
general-sibling combinator '~' is required for a bug in Chrome: */
#textAreaToggle:checked ~ #textarea + label::before {
content: 'Hide ';
}
Here's a linearization option on simple data that uses tools from scikit learn.
Given
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import FunctionTransformer
np.random.seed(123)
# General Functions
def func_exp(x, a, b, c):
"""Return values from a general exponential function."""
return a * np.exp(b * x) + c
def func_log(x, a, b, c):
"""Return values from a general log function."""
return a * np.log(b * x) + c
# Helper
def generate_data(func, *args, jitter=0):
"""Return a tuple of arrays with random data along a general function."""
xs = np.linspace(1, 5, 50)
ys = func(xs, *args)
noise = jitter * np.random.normal(size=len(xs)) + jitter
xs = xs.reshape(-1, 1) # xs[:, np.newaxis]
ys = (ys + noise).reshape(-1, 1)
return xs, ys
transformer = FunctionTransformer(np.log, validate=True)
Code
Fit exponential data
# Data
x_samp, y_samp = generate_data(func_exp, 2.5, 1.2, 0.7, jitter=3)
y_trans = transformer.fit_transform(y_samp) # 1
# Regression
regressor = LinearRegression()
results = regressor.fit(x_samp, y_trans) # 2
model = results.predict
y_fit = model(x_samp)
# Visualization
plt.scatter(x_samp, y_samp)
plt.plot(x_samp, np.exp(y_fit), "k--", label="Fit") # 3
plt.title("Exponential Fit")
Fit log data
# Data
x_samp, y_samp = generate_data(func_log, 2.5, 1.2, 0.7, jitter=0.15)
x_trans = transformer.fit_transform(x_samp) # 1
# Regression
regressor = LinearRegression()
results = regressor.fit(x_trans, y_samp) # 2
model = results.predict
y_fit = model(x_trans)
# Visualization
plt.scatter(x_samp, y_samp)
plt.plot(x_samp, y_fit, "k--", label="Fit") # 3
plt.title("Logarithmic Fit")
Details
General Steps
x
, y
or both)np.exp()
) and fit to original dataAssuming our data follows an exponential trend, a general equation+ may be:
We can linearize the latter equation (e.g. y = intercept + slope * x) by taking the log:
Given a linearized equation++ and the regression parameters, we could calculate:
A
via intercept (ln(A)
)B
via slope (B
)Summary of Linearization Techniques
Relationship | Example | General Eqn. | Altered Var. | Linearized Eqn.
-------------|------------|----------------------|----------------|------------------------------------------
Linear | x | y = B * x + C | - | y = C + B * x
Logarithmic | log(x) | y = A * log(B*x) + C | log(x) | y = C + A * (log(B) + log(x))
Exponential | 2**x, e**x | y = A * exp(B*x) + C | log(y) | log(y-C) = log(A) + B * x
Power | x**2 | y = B * x**N + C | log(x), log(y) | log(y-C) = log(B) + N * log(x)
+Note: linearizing exponential functions works best when the noise is small and C=0. Use with caution.
++Note: while altering x data helps linearize exponential data, altering y data helps linearize log data.
Inside config folder open app.php
Change
'debug' => false,
to
'debug' => true,
My problem resolved by this what changes i have done in .net core Do this changes in Appsetting.json
Server=***;Database=***;Persist Security Info=False;User ID=***; Password=***;MultipleActiveResultSets=False;Encrypt=False;TrustServerCertificate=False;Connection Timeout=30
and Do following changes in Package console manager
Scaffold-DbContext "Server=***;Database=***;Persist Security Info=False;User ID=***; Password=***;MultipleActiveResultSets=False;Encrypt=False;TrustServerCertificate=False;Connection Timeout=30;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context DatabaseContext -f
Happy coding
The other answers (including the accepted ones) are good, but if you already use Java8, you can do the following (in a shorter, newer way):
textField.addActionListener(
ae -> {
//dostuff
}
);
As the accepted answer told, you can simply react with an ActionListener
, which catches the Enter-Key.
However, my approach takes benefit of the functional concepts which was introduced in Java 8.
If you want to use the same action for example for a button and the JTextField, you can do the following:
ActionListener l = ae -> {
//do stuff
}
button.addActionListener(l);
textField.addActionListener(l);
If further explaination is needed, please let me know!
As a humble beginner in the world of programming, and flicking through all the answers here after seeing this word used a lot in apparently slightly different ways in different places, I found reading the Wikipedia page on Bootstrapping (duh! I didn't think of it either at first) is very informative to understand differences in use of this word. Could it be......on extremely rare occasions......Wikipedia might even have better explanations of certain terms than....(redacted)? Will they bring in rep points on Wikipedia though?
To me, it seems all the meanings something to do with: start with something as simple as possible Thing1, make something slightly more complex with that Thing2, and now you can use Thing2 to do some kind of tasks more efficiently and quickly than you could originally with Thing1. Then repeat from Thing2 to Thing 3 ad infinitum...
I see it as closely connected to both biological evolution and 'Layers of Abstraction' (newbies like me see, ahem, Wikipedia, cough) - the evolution from 1940's computers with switches, machine code, Assembly, C, Python, AIs you can give all kinds of complex instructions to like "make the %4^% dinner to my default &^$% requirements and clean the floor you %$£"@:~" in drunken slang English or Amazon tribal dialect without them 'raising an exception' (for newbies again...you guessed it) - missed out lot of links there due to simple ignorance.
Then in certain specific software meanings: Meaning1: Thing1 is used to load latest version of Thing2 (because of course Thing2 will be bigger than Thing1, just as Thing3 will be be bigger than Thing2).
Meaning2: Thing1 is a lower level language (closer to 1001011100....011001 than print("Hello, ", user.name)) used to write a little bit of the higher language of Thing2, then this little bit of Thing2 is used to expand Thing2 itself from baby vocabulary level towards adult vocabulary level (Thing2 starts to be processed, or to use correct technical term 'compiled', by the baby version of itself (it's a clever baby!), whereas the baby version of Thing2 itself could of course only be compiled by Thing1, cause it can't exist before it exists, right duh!), then child version of Thing2 compiles Surly Teenager version of Thing2, at which point programming community decides whether Surly Teenager's 'issues' (software term and metaphor term!) are worth spending enough time resolving to be accepted long term, or to abandon them to (not sure where to take the analogy here).
If yes, then Thing2 has 'Bootstrapped' itself (possibly a few times) from babyhood to adulthood: "the child is the father of the man" (Wordsworth, suggest don't try looking up the quote or the author on Stack Overflow).
A simpler solution on recent versions of tmux (tested on 1.9) you can now do :
tmux detach -a
-a
is for all other client on this session except the current one
You can alias it in your .[bash|zsh]rc
alias takeover="tmux detach -a"
Workflow: You can connect to your session normally, and if you are bothered by another session that forced down your tmux window size you can simply call takeover
.
If your array is always sequential and starts at 0, then you can do this:
array[${#array[@]}]='foo'
# gets the length of the array
${#array_name[@]}
If you inadvertently use spaces between the equal sign:
array[${#array[@]}] = 'foo'
Then you will receive an error similar to:
array_name[3]: command not found
it's easy to rewrite this code in C#...
This method works if your value it's between 2 substrings !
for example:
stringContent = "[myName]Alex[myName][color]red[color][etc]etc[etc]"
calls should be:
myNameValue = SplitStringByASubstring(stringContent , "[myName]")
colorValue = SplitStringByASubstring(stringContent , "[color]")
etcValue = SplitStringByASubstring(stringContent , "[etc]")
Try this:
SELECT filename,Dates,Status
FROM TableName
WHERE Dates In (SELECT MAX(Dates) FROM TableName GROUP BY filename)
Yes I believe it's possible but you might have to implement your own classloader. I have never done it but that is the path I would probably look at.
An easy fix to this question is to add '[' in the start of your json file, and ending it with a ']'. This solved it for me.
I've tested it using the following code:
$emails = ['[email protected]', '[email protected]','[email protected]'];
Mail::send('emails.welcome', [], function($message) use ($emails)
{
$message->to($emails)->subject('This is test e-mail');
});
var_dump( Mail:: failures());
exit;
Result - empty array for failures.
But of course you need to configure your app/config/mail.php
properly. So first make sure you can send e-mail just to one user and then test your code with many users.
Moreover using this simple code none of my e-mails were delivered to free mail accounts, I got only emails to inboxes that I have on my paid hosting accounts, so probably they were caught by some filters (it's maybe simple topic/content issue but I mentioned it just in case you haven't received some of e-mails) .
This is a bit of an old question, but I thought I would contribute my 2 cents anyway since this thread came up in conversation today.
This doesn't exactly answer why is there no const? but how to make your classes immutable. (Unfortunately I have not enough reputation yet to post as a comment to the accepted answer)
The way to guarantee immutability on an object is to design your classes more carefully to be immutable. This requires a bit more care than a mutable class.
This goes back to Josh Bloch's Effective Java Item 15 - Minimize Mutability. If you haven't read the book, pick up a copy and read it over a few times I guarantee it will up your figurative "java game".
In item 15 Bloch suggest that you should limit the mutability of classes to ensure the object's state.
To quote the book directly:
An immutable class is simply a class whose instances cannot be modified. All of the information contained in each instance is provided when it is created and is fixed for the lifetime of the object. The Java platform libraries contain many immutable classes, including String, the boxed primitive classes, and BigInte- ger and BigDecimal. There are many good reasons for this: Immutable classes are easier to design, implement, and use than mutable classes. They are less prone to error and are more secure.
Bloch then describes how to make your classes immutable, by following 5 simple rules:
final
).final
.private
. For more details I highly recommend picking up a copy of the book.
reed these links
http://tools.android.com/tech-docs/new-build-system/version-compatibility https://developer.android.com/studio/releases/gradle-plugin.html
in android studio version 2+, use this in gradle config
android{
..
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
incremental = false;
}
...
}
after 3 days of search and test :(, this solve "rebuild for any run"
Generally speaking, this is the pattern I use:
If you want to place your address in google map then easy way to use following
Intent searchAddress = new Intent(Intent.ACTION_VIEW,Uri.parse("geo:0,0?q="+address));
startActivity(searchAddress);
OR
if you needed to get lat long from your address then use Google Place Api following
create a method that returns a JSONObject with the response of the HTTP Call like following
public static JSONObject getLocationInfo(String address) {
StringBuilder stringBuilder = new StringBuilder();
try {
address = address.replaceAll(" ","%20");
HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
stringBuilder = new StringBuilder();
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObject;
}
now pass that JSONObject to getLatLong() method like following
public static boolean getLatLong(JSONObject jsonObject) {
try {
longitute = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lng");
latitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lat");
} catch (JSONException e) {
return false;
}
return true;
}
I hope this helps to you nd others..!! Thank you..!!
Your code contains dataType: json.
In this case jQuery evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner. Any malformed JSON is rejected and a parse error is thrown. An empty response is also rejected.
The server should return a response of null
or {}
instead.
Sample:
Label label = new Label();
label.HorizontalContentAlignment = HorizontalAlignment.Center;
The sorted()
function is very helpful for this. Use the sorted function
to order the list, then simply return the middle value (or average the two middle
values if the list contains an even amount of elements).
def median(lst):
sortedLst = sorted(lst)
lstLen = len(lst)
index = (lstLen - 1) // 2
if (lstLen % 2):
return sortedLst[index]
else:
return (sortedLst[index] + sortedLst[index + 1])/2.0
You're declaring everything in the parent page. So the references to window
and document
are to the parent page's. If you want to do stuff to the iframe
's, use iframe || iframe.contentWindow
to access its window
, and iframe.contentDocument || iframe.contentWindow.document
to access its document
.
There's a word for what's happening, possibly "lexical scope": What is lexical scope?
The only context of a scope is this. And in your example, the owner of the method is doc
, which is the iframe
's document
. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.
This is how I would write it:
(function () {
var dom, win, doc, where, iframe;
iframe = document.createElement('iframe');
iframe.src = "javascript:false";
where = document.getElementsByTagName('script')[0];
where.parentNode.insertBefore(iframe, where);
win = iframe.contentWindow || iframe;
doc = iframe.contentDocument || iframe.contentWindow.document;
doc.open();
doc._l = (function (w, d) {
return function () {
w.vanishing_global = new Date().getTime();
var js = d.createElement("script");
js.src = 'test-vanishing-global.js?' + w.vanishing_global;
w.name = "foobar";
d.foobar = "foobar:" + Math.random();
d.foobar = "barfoo:" + Math.random();
d.body.appendChild(js);
};
})(win, doc);
doc.write('<body onload="document._l();"></body>');
doc.close();
})();
The aliasing of win
and doc
as w
and d
aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe
's stuff. If you want to access the parent's, you still use window
and document
.
I'm not sure what the implications are of adding methods to a document
(doc
in this case), but it might make more sense to set the _l
method on win
. That way, things can be run without a prefix...such as <body onload="_l();"></body>
Try the following:
POJO pojo = mapper.convertValue(singleObject, POJO.class);
or:
List<POJO> pojos = mapper.convertValue(
listOfObjects,
new TypeReference<List<POJO>>() { });
See conversion of LinkedHashMap for more information.
I've done something like this.
private void Form_FormClosing(object sender, FormClosingEventArgs e)
{
if ((sender as Form).ActiveControl is Button)
{
//CloseButton
}
else
{
//The X has been clicked
}
}
If you only have two items, you can do this:
.social {
width: 330px;
height: 75px;
float: right;
text-align: left;
padding: 10px 0;
border: none;
}
.social:first-child {
padding-top:0;
border-bottom: dotted 1px #6d6d6d;
}
You can use the -TotalCount
parameter of the Get-Content
cmdlet to read the first n
lines, then use Select-Object
to return only the n
th line:
Get-Content file.txt -TotalCount 9 | Select-Object -Last 1;
Per the comment from @C.B. this should improve performance by only reading up to and including the n
th line, rather than the entire file. Note that you can use the aliases -First
or -Head
in place of -TotalCount
.
I am using Python 3.6 and using a comma between Exception and e does not work. I need to use the following syntax (just for anyone wondering)
try:
connection = manager.connect("I2Cx")
except KeyError as e:
print(e.message)
A static readonly field is advantageous when exposing to other assemblies a value that might change in a later version.
For instance, suppose assembly X
exposes a constant as follows:
public const decimal ProgramVersion = 2.3;
If assembly Y
references X
and uses this constant, the value 2.3
will be baked into assembly Y
when compiled. This means that
if X
is later recompiled with the constant set to 2.4, Y
will still
use the old value of 2.3 until Y
is recompiled. A static
readonly field avoids this problem.
Another way of looking at this is that any value that might change in the future is not constant by definition, and so should not be represented as one.
The following code fragment should return the size in bytes of any object passed to it, so long as it can be serialized. I got this from a colleague at Quixant to resolve a problem of writing to SRAM on a gaming platform. Hope it helps out. Credit and thanks to Carlo Vittuci.
/// <summary>
/// Calculates the lenght in bytes of an object
/// and returns the size
/// </summary>
/// <param name="TestObject"></param>
/// <returns></returns>
private int GetObjectSize(object TestObject)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
byte[] Array;
bf.Serialize(ms, TestObject);
Array = ms.ToArray();
return Array.Length;
}
Derive from dict and and implement __getattr__
and __setattr__
.
Or you can use Bunch which is very similar.
I don't think it's possible to monkeypatch built-in dict class.
bool vExist = false;
int vSelectValue = 1;
List<int> vList = new List<int>();
vList.Add(1);
vList.Add(2);
IEnumerable vRes = (from n in vListwhere n == vSelectValue);
if (vRes.Count > 0) {
vExist = true;
}
I don't think that you need to use each()
, you can use standard for loop
var children = $element.children().not(".pb-sortable-placeholder");
for (var i = 0; i < children.length; i++) {
var currentChild = children.eq(i);
// whatever logic you want
var oldPosition = currentChild.data("position");
}
this way you can have the standard for loop features like break
and continue
works by default
also, the debugging will be easier
I had the same problem when using a 32 bit version of java in a 64 bit environment. When using 64 java in a 64 OS it was ok.
use style white-space: pre
the <pre>
tag also modifies the text format which may be undesirable.
In this piece of code the height of left panel will gets adjusted to the height of right panel dynamically...
function resizeDiv() {
var rh=$('.pright').height()+'px'.toString();
$('.pleft').css('height',rh);
}
You can try this here http://jsfiddle.net/SriharshaCR/7q585k1x/9/embedded/result/
Appart from setting maven source url to your gradle, I would suggest to add both design and appcompat libraries. Currently the latest version is 26.1.0
maven {
url "https://maven.google.com"
}
...
compile 'com.android.support:appcompat-v7:26.1.0'
compile 'com.android.support:design:26.1.0'
In order to get Android device name you have to add only a single line of code:
android.os.Build.MODEL;
Found here: getting-android-device-name
There is a package that converts it for you and returns the svg as a string to implement into your reactJS file.
Create a Dockerfile
#
# Build stage
#
FROM maven:3.6.3-jdk-11-slim AS build
WORKDIR usr/src/app
COPY . ./
RUN mvn clean package
#
# Package stage
#
FROM openjdk:11-jre-slim
ARG JAR_NAME="project-name"
WORKDIR /usr/src/app
EXPOSE ${HTTP_PORT}
COPY --from=build /usr/src/app/target/${JAR_NAME}.jar ./app.jar
CMD ["java","-jar", "./app.jar"]
Here's a simple little function that will rbind two datasets together after auto-detecting what columns are missing from each and adding them with all NA
s.
For whatever reason this returns MUCH faster on larger datasets than using the merge
function.
fastmerge <- function(d1, d2) {
d1.names <- names(d1)
d2.names <- names(d2)
# columns in d1 but not in d2
d2.add <- setdiff(d1.names, d2.names)
# columns in d2 but not in d1
d1.add <- setdiff(d2.names, d1.names)
# add blank columns to d2
if(length(d2.add) > 0) {
for(i in 1:length(d2.add)) {
d2[d2.add[i]] <- NA
}
}
# add blank columns to d1
if(length(d1.add) > 0) {
for(i in 1:length(d1.add)) {
d1[d1.add[i]] <- NA
}
}
return(rbind(d1, d2))
}
Looks like you've not encapsulated your string properly. Try this:
INSERT INTO custorder VALUES ('Kevin','yes'), STR_TO_DATE('1-01-2012', '%d-%m-%Y');
Alternatively, you can do the following but it is not recommended. Make sure that you use STR_TO-DATE it is because when you are developing web applications you have to explicitly convert String to Date which is annoying. Use first One.
INSERT INTO custorder VALUES ('Kevin','yes'), '2012-01-01';
I'm not confident that the above SQL is valid, however, and you may want to move the date part into the brackets. If you can provide the exact error you're getting, I might be able to more directly help with the issue.
Implement onClick() method in your Activity/Fragment public class MainActivity extends Activity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onClick(View v) {
switch (itemId) {
// if you call the fragment with nevigation bar then used.
case R.id.nav_menu1:
fragment = new IntroductionFragment();
break;
// if call activity with nevigation bar then used.
case R.id.nav_menu6:
Intent i = new Intent(MainActivity.this, YoutubeActivity.class);
startActivity(i);
// default method for handling onClick Events..
}
}
Assuming you have already installed Flutter Plugin if you have not installed then go to Android Studio IDE setting/preferences(MAC) --> plugin--> Browse Repositories and search Flutter then install and restart IDE
Now follow these steps:-
First of all go to https://flutter.io/get-started/install/ and download the Fluter SDK
Then extract the zip file in any specified folder
Now give this path as Fluter SDK
That's it.
I had a similar problem with a request to a non-SSL service.
This blog suggested vaguely to try URI encoding the URL that is passed to 'get': http://www.loudthinking.org/2010/02/ruby-eoferror-end-of-file-reached.html
I took a shot at it, based on desperation, and in my limiting testing this seems to have fixed it for me. My new code is:
@http = Net::HTTP.new('domain.com')
@http = @http.start
url = 'http://domain.com/requested_url?blah=blah&etc=1'
req = Net::HTTP::Get.new(URI.encode(url))
req.basic_auth USERNAME, API_KEY
res = @http.request(req)
Note that I use @http.start as I want to maintain the HTTP session over multiple requests. Other than that, you might like to try the most relevant part which is: URI.encode(url) inside the get call
It completely depends on the contexts in which the data structure is needed. For example, if you are creating items to be used by other functions or services using List is the perfect way to accomplish it.
Now if you have a list of items and you just want to display them, say on a web page array is the container you need to use.
There are several ways this can be accomplished.
You can make use of the builtin string function .replace()
to replace all occurrences of quotes in a given string:
>>> s = '"abcd" efgh'
>>> s.replace('"', '')
'abcd efgh'
>>>
You can use the string function .join()
and a generator expression to remove all quotes from a given string:
>>> s = '"abcd" efgh'
>>> ''.join(c for c in s if c not in '"')
'abcd efgh'
>>>
You can use a regular expression to remove all quotes from given string. This has the added advantage of letting you have control over when and where a quote should be deleted:
>>> s = '"abcd" efgh'
>>> import re
>>> re.sub('"', '', s)
'abcd efgh'
>>>
To allow single quotes within doubule quoted string for the purpose of json, you double the single quote. {"X": "What's the question"} ==> {"X": "What''s the question"}
https://codereview.stackexchange.com/questions/69266/json-conversion-to-single-quotes
The \' sequence is invalid.
I was able to get this work. I added the following to my custom CSS:
.wpcf7-form textarea{
width: 100% !important;
height:50px;
}
With some error handling...
uint key = 0;
string s = "HKEY_LOCAL_MACHINE";
try
{
key = (uint)Enum.Parse(typeof(baseKey), s);
}
catch(ArgumentException)
{
//unknown string or s is null
}
I ran into this error because I was trying to pass in a date from localStorage
. Passing the date into a new Date
object, and then calling .toISOString() did the trick for me:
const dateFromStorage = localStorage.getItem('someDate');
const date = new Date(dateFromStorage);
const momentDate = moment(date.toISOString());
This suppressed any warnings in the console.
customerssalary.Average();
customerssalary.Sum();
For Oracle 11g, I was able to change the column attribute as follows:
ALTER TABLE tablename MODIFY columnname datatype NOT NULL;
Otherwise abatichev's answer seemed good. You can't repeat the alter - it complains (at least in SQL Developer) that the column is already not null.
I instinctively read it as "different from". "!=" hits me milliseconds after.
This will work nicely if it is in a gem lib directory and this is the tokenizer.rb
require_relative 'tokenizer/main'
Use std::make_pair
:
revenue.push_back(std::make_pair("string",map[i].second));
Use the Key
keyword in your select will work, like below.
product.Select(m => new {Key m.CategoryId, Key m.CategoryName}).Distinct();
I realize this is bringing up an old thread but figured it might help some people. I generally code in VB.NET when working with .NET so Key
may translate differently into C#.
As brb tea says, depends on the database implementation and the algorithm they use: MVCC or Two Phase Locking.
CUBRID (open source RDBMS) explains the idea of this two algorithms:
- Two-phase locking (2PL)
The first one is when the T2 transaction tries to change the A record, it knows that the T1 transaction has already changed the A record and waits until the T1 transaction is completed because the T2 transaction cannot know whether the T1 transaction will be committed or rolled back. This method is called Two-phase locking (2PL).
- Multi-version concurrency control (MVCC)
The other one is to allow each of them, T1 and T2 transactions, to have their own changed versions. Even when the T1 transaction has changed the A record from 1 to 2, the T1 transaction leaves the original value 1 as it is and writes that the T1 transaction version of the A record is 2. Then, the following T2 transaction changes the A record from 1 to 3, not from 2 to 4, and writes that the T2 transaction version of the A record is 3.
When the T1 transaction is rolled back, it does not matter if the 2, the T1 transaction version, is not applied to the A record. After that, if the T2 transaction is committed, the 3, the T2 transaction version, will be applied to the A record. If the T1 transaction is committed prior to the T2 transaction, the A record is changed to 2, and then to 3 at the time of committing the T2 transaction. The final database status is identical to the status of executing each transaction independently, without any impact on other transactions. Therefore, it satisfies the ACID property. This method is called Multi-version concurrency control (MVCC).
The MVCC allows concurrent modifications at the cost of increased overhead in memory (because it has to maintain different versions of the same data) and computation (in REPETEABLE_READ level you can't loose updates so it must check the versions of the data, like Hiberate does with Optimistick Locking).
In 2PL Transaction isolation levels control the following:
Whether locks are taken when data is read, and what type of locks are requested.
How long the read locks are held.
Whether a read operation referencing rows modified by another transaction:
Block until the exclusive lock on the row is freed.
Retrieve the committed version of the row that existed at the time the statement or transaction started.
Read the uncommitted data modification.
Choosing a transaction isolation level does not affect the locks that are acquired to protect data modifications. A transaction always gets an exclusive lock on any data it modifies and holds that lock until the transaction completes, regardless of the isolation level set for that transaction. For read operations, transaction isolation levels primarily define the level of protection from the effects of modifications made by other transactions.
A lower isolation level increases the ability of many users to access data at the same time, but increases the number of concurrency effects, such as dirty reads or lost updates, that users might encounter.
Concrete examples of the relation between locks and isolation levels in SQL Server (use 2PL except on READ_COMMITED with READ_COMMITTED_SNAPSHOT=ON)
READ_UNCOMMITED: do not issue shared locks to prevent other transactions from modifying data read by the current transaction. READ UNCOMMITTED transactions are also not blocked by exclusive locks that would prevent the current transaction from reading rows that have been modified but not committed by other transactions. [...]
READ_COMMITED:
REPETEABLE_READ: Shared locks are placed on all data read by each statement in the transaction and are held until the transaction completes.
SERIALIZABLE: Range locks are placed in the range of key values that match the search conditions of each statement executed in a transaction. [...] The range locks are held until the transaction completes.
You should check MSDN for Math.Round
:
The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding to nearest, or banker's rounding.
You can specify the behavior of Math.Round
using an overload:
Math.Round(2.5, 0, MidpointRounding.AwayFromZero); // gives 3
Math.Round(2.5, 0, MidpointRounding.ToEven); // gives 2
One straight forward way to ensure the object is initialized without any error is to test the object's type instance.
Here is an example :
p = SomeClass(param1=_param1_value)
self.assertTrue(isinstance(p, SomeClass))
That's because that's an SQL function, not PHP. You can use PDO::lastInsertId()
.
Like:
$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();
If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:
$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();
string saveStaff = "INSERT into student (stud_id,stud_name) " + " VALUES ('" + SI+ "', '" + SN + "');";
cmd = new SqlCommand(saveStaff,con);
cmd.ExecuteNonQuery();
I'm guessing that you want something like
SELECT tab1.a, tab2.b, tab3.c, tab4.d
FROM table1 tab1
JOIN table2 tab2 ON (tab1.fg = tab2.fg)
LEFT OUTER JOIN table4 tab4 ON (tab1.ss = tab4.ss)
LEFT OUTER JOIN table3 tab3 ON (tab4.xya = tab3.xya and tab3.desc = 'XYZ')
LEFT OUTER JOIN table5 tab5 on (tab4.kk = tab5.kk AND
tab3.dd = tab5.dd)
This problem normally appears while copy pasting the tag lib URL from the internet. Usually the quotes ""
in which the URL http://www.springframework.org/tags is embedded might not be correct. Try removing quotes and type them manually. This resolved the issue for me.
It very much depend on the program you're using. Different programs (Emacs, vi, sed, and Perl) use slightly different regular expressions. In this case, I'd say that in the first pattern, the last "+" should be removed.
This is happening because the user 'sarin' is the actual owner of the database "dbemployee" - as such, they can only have db_owner, and cannot be assigned any further database roles.
Nor do they need to be. If they're the DB owner, they already have permission to do anything they want to within this database.
(To see the owner of the database, open the properties of the database. The Owner is listed on the general tab).
To change the owner of the database, you can use sp_changedbowner or ALTER AUTHORIZATION (the latter being apparently the preferred way for future development, but since this kind of thing tends to be a one off...)
First you need to keep copy of following somewhere in your hard disk.
C:\xampp\mysql\backup
C:\xampp\mysql\data
After that
Copy every thing inside "C:\xampp\mysql\backup" and paste and replace it in
"C:\xampp\mysql\data"
Now your mysql will work in phpmyadmin but your tables will show "Table not found in engine"
For this you will have to go to the copy of "backup and data folders" which have created in your hard disk and there in the data folder copy "ibdata1" file and past and replace in the "C:\xampp\mysql\data".
Now your tables data will be available.
$scriptBlock = [Scriptblock]::Create(@'
echo 'before'
ipconfig /all
echo 'after'
'@)
Invoke-Command -ComputerName AD01 -ScriptBlock $scriptBlock
I had used JCL about 2 years back so cannot write a code for you but here is the idea;
again i apologize for solution without code, but i am out of touch by 2 yrs+
You can use overflow-y: scroll
for vertical scrolling.
<div style="overflow-y:scroll; height:400px; background:gray">_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
_x000D_
</div>
_x000D_
In my case all of them did not work and finally it was
msiexec /i "msinamebla.msi" INSTALLFOLDER="C:\test\" /qb
I checked the log.txt as described by ezzadeen and found "INSTALLFOLDER" in there.
I use []
.
A blazingly faster approach is to do the multiplication in a vectorized manner instead of looping over the list. Numpy has already provided a very simply and handy way for this that you can use.
>>> import numpy as np
>>>
>>> my_list = np.array([1, 2, 3, 4, 5])
>>>
>>> my_list * 5
array([ 5, 10, 15, 20, 25])
Note that this doesn't work with Python's native lists. If you multiply a number with a list it will repeat the items of the as the size of that number.
In [15]: my_list *= 1000
In [16]: len(my_list)
Out[16]: 5000
If you want a pure Python-based approach using a list comprehension is basically the most Pythonic way to go.
In [6]: my_list = [1, 2, 3, 4, 5]
In [7]: [5 * i for i in my_list]
Out[7]: [5, 10, 15, 20, 25]
Beside list comprehension, as a pure functional approach, you can also use built-in map()
function as following:
In [10]: list(map((5).__mul__, my_list))
Out[10]: [5, 10, 15, 20, 25]
This code passes all the items within the my_list
to 5
's __mul__
method and returns an iterator-like object (in python-3.x). You can then convert the iterator to list using list()
built in function (in Python-2.x you don't need that because map
return a list by default).
In [18]: %timeit [5 * i for i in my_list]
463 ns ± 10.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [19]: %timeit list(map((5).__mul__, my_list))
784 ns ± 10.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [20]: %timeit [5 * i for i in my_list * 100000]
20.8 ms ± 115 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [21]: %timeit list(map((5).__mul__, my_list * 100000))
30.6 ms ± 169 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [24]: arr = np.array(my_list * 100000)
In [25]: %timeit arr * 5
899 µs ± 4.98 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
This will only work for windows which are opened by using window.open(); method. Try this
var tmp=window.open(params);
tmp.close();
json.dumps()
is much more than just making a string out of a Python object, it would always produce a valid JSON string (assuming everything inside the object is serializable) following the Type Conversion Table.
For instance, if one of the values is None
, the str()
would produce an invalid JSON which cannot be loaded:
>>> data = {'jsonKey': None}
>>> str(data)
"{'jsonKey': None}"
>>> json.loads(str(data))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)
But the dumps()
would convert None
into null
making a valid JSON string that can be loaded:
>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}
You could also use box-shadow
property with higher value of blur and rgba()
color to set opacity level.
Sounds like a better choice in your case.
box-shadow: 0 30px 40px rgba(0,0,0,.1);
treeset is an ordered set, but you can't access via an items index, just iterate through or go to beginning/end.
On my 64 bit system I noticed that the following directory existed:
/usr/include/c++/4.4/x86_64-linux-gnu/32/bits
It would then make sense that on my 32 bit system that had been setup for 64bit cross compiling there should be a corresponding directory like:
/usr/include/c++/4.4/i686-linux-gnu/64/bits
I double checked and this directory did not exist. Running g++
with the verbose parameter showed that the compiler was actually looking for something in this location:
jesse@shalored:~/projects/test$ g++ -v -m64 main.cpp
Using built-in specs.
Target: i686-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 4.4.4-14ubuntu5' --with-bugurl=file:///usr/share/doc/gcc-4.4/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.4 --enable-shared --enable-multiarch --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.4 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-objc-gc --enable-targets=all --disable-werror --with-arch-32=i686 --with-tune=generic --enable-checking=release --build=i686-linux-gnu --host=i686-linux-gnu --target=i686-linux-gnu
Thread model: posix
gcc version 4.4.5 (Ubuntu/Linaro 4.4.4-14ubuntu5)
COLLECT_GCC_OPTIONS='-v' '-m64' '-shared-libgcc' '-mtune=generic'
/usr/lib/gcc/i686-linux-gnu/4.4.5/cc1plus -quiet -v -imultilib 64 -D_GNU_SOURCE main.cpp -D_FORTIFY_SOURCE=2 -quiet -dumpbase main.cpp -m64 -mtune=generic -auxbase main -version -fstack-protector -o /tmp/ccMvIfFH.s
ignoring nonexistent directory "/usr/include/c++/4.4/i686-linux-gnu/64"
ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu"
ignoring nonexistent directory "/usr/lib/gcc/i686-linux-gnu/4.4.5/../../../../i686-linux-gnu/include"
#include "..." search starts here:
#include <...> search starts here:
/usr/include/c++/4.4
/usr/include/c++/4.4/backward
/usr/local/include
/usr/lib/gcc/i686-linux-gnu/4.4.5/include
/usr/lib/gcc/i686-linux-gnu/4.4.5/include-fixed
/usr/include/x86_64-linux-gnu
/usr/include
End of search list.
GNU C++ (Ubuntu/Linaro 4.4.4-14ubuntu5) version 4.4.5 (i686-linux-gnu)
compiled by GNU C version 4.4.5, GMP version 4.3.2, MPFR version 3.0.0-p3.
GGC heuristics: --param ggc-min-expand=98 --param ggc-min-heapsize=128197
Compiler executable checksum: 1fe36891f4a5f71e4a498e712867261c
In file included from main.cpp:1:
/usr/include/c++/4.4/iostream:39: fatal error: bits/c++config.h: No such file or directory
compilation terminated.
The error regarding the ignoring nonexistent directory
was the clue. Unfortunately, I still don't know what package I need to install to have this directory show up so I just copied the /usr/include/c++/4.4/x86_64-linux-gnu/bits
directory from my 64 bit machine to /usr/include/c++/4.4/i686-linux-gnu/64/bits
on my 32 machine.
Now compiling with just the -m64
works correctly. The major drawback is that this is still not the correct way to do things and I am guessing the next time Update Manager installs and update to g++ things may break.
This is not only applicable in Modernizer. I see some site implement like below to check whether it has javascript support or not.
<body class="no-js">
<script>document.body.classList.remove('no-js');</script>
...
</body>
If javascript support is there, then it will remove no-js
class. Otherwise no-js
will remain in the body tag. Then they control the styles in the css when no javascript support.
.no-js .some-class-name {
}
File extensions for cryptographic certificates aren't really as standardized as you'd expect. Windows by default treats double-clicking a .crt
file as a request to import the certificate into the Windows Root Certificate store, but treats a .cer
file as a request just to view the certificate. So, they're different in the sense that Windows has some inherent different meaning for what happens when you double click each type of file.
But the way that Windows handles them when you double-click them is about the only difference between the two. Both extensions just represent that it contains a public certificate. You can rename a certificate file to use one extension in place of the other in any system or configuration file that I've seen. And on non-Windows platforms (and even on Windows), people aren't particularly careful about which extension they use, and treat them both interchangeably, as there's no difference between them as long as the contents of the file are correct.
Making things more confusing is that there are two standard ways of storing certificate data in a file: One is a "binary" X.509 encoding, and the other is a "text" base64 encoding that usually starts with "-----BEGIN CERTIFICATE-----
". These encode the same data but in different ways. Most systems accept both formats, but, if you need to, you can convert one to the other via openssl or other tools. The encoding within a certificate file is really independent of which extension somebody gave the file.
Along the lines of the accepted answer, if you have a JSON text sample you can plug it in to this converter, select your options and generate the C# code.
If you don't know the type at runtime, this topic looks like it would fit.
If you need ContainsAny with a specific StringComparison
(for example to ignore case) then you can use this String Extentions method.
public static class StringExtensions
{
public static bool ContainsAny(this string input, IEnumerable<string> containsKeywords, StringComparison comparisonType)
{
return containsKeywords.Any(keyword => input.IndexOf(keyword, comparisonType) >= 0);
}
}
Usage with StringComparison.CurrentCultureIgnoreCase
:
var input = "My STRING contains Many Substrings";
var substrings = new[] {"string", "many substrings", "not containing this string" };
input.ContainsAny(substrings, StringComparison.CurrentCultureIgnoreCase);
// The statement above returns true.
”xyz”.ContainsAny(substrings, StringComparison.CurrentCultureIgnoreCase);
// This statement returns false.
If you are just experimenting you can use babel-node
command line tool to try out the new JavaScript features
Install babel-cli
into your project
$ npm install --save-dev babel-cli
Install the presets
$ npm install --save-dev babel-preset-es2015 babel-preset-es2017
Setup your babel presets
Create .babelrc
in the project root folder with the following contents:
{ "presets": ["es2015","es2017"] }
Run your script with babel-node
$ babel-node helloz.js
This is only for development and testing but that seems to be what you are doing. In the end you'll want to set up webpack (or something similar) to transpile all your code for production
If you want to run the code somewhere else, webpack can help and here is the simplest configuration I could work out:
Another way is using set data type.
Some characteristic of Sets: Sets are unordered, can include mixed data types, elements in a set cannot be repeated, are mutable.
Solving your question:
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
sorted(set(df.A))
The answer in List type:
[1, 2, 3, 6, 8]
The characters you are reading on your screen now each have a numerical value. In the ASCII format, for example, the letter 'A' is 65, 'B' is 66, and so on. If you look at a table of characters available in ASCII you will see that it isn't much use for someone who wishes to write something in Mandarin, Arabic, or Japanese. For characters / words from those languages to be displayed we needed another system of encoding them to and from numbers stored in computer memory.
UTF-8 is just one of the encoding methods that were invented to implement this requirement. It lets you write text in all kinds of languages, so French accents will appear perfectly fine, as will text like this
???? ????? (Bzia zbasa), ???????, Ç'kemi, ???, and even right-to-left writing such as this ?????? ?????
If you copy and paste the above text into notepad and then try to save the file as ANSI (another format) you will receive a warning that saving in this format will lose some of the formatting. Accept it, then re-load the text file and you'll see something like this
???? ????? (Bzia zbasa), ???????, Ç'kemi, ???, and even right-to-left writing such as this ?????? ?????
Did you read clang
documentation ? You're probably looking for -emit-llvm
.
Just run this command:
git reset --hard
Removing from an array itself is not simple, as you then have to deal with resizing. This is one of the great advantages of using something like a List<int>
instead. It provides Remove
/RemoveAt
in 2.0, and lots of LINQ extensions for 3.0.
If you can, refactor to use a List<>
or similar.
I had to use:
table, tbody {
width: 100%;
}
The table
alone wasn't enough, the tbody
was also needed for it to work for me.
there is no CSS selector for selecting a parent of a selected child.
you could do it with JavaScript
You can push your local branch to a new remote branch like so:
git push origin master:test
(Assuming origin
is your remote, master
is your local branch name and test
is the name of the new remote branch, you wish to create.)
If at the same time you want to set up your local branch to track the newly created remote branch, you can do so with -u
(on newer versions of Git) or --set-upstream
, so:
git push -u origin master:test
or
git push --set-upstream origin master:test
...will create a new remote branch, named test
, in remote repository origin
, based on your local master
, and setup your local master
to track it.
Direct Javascript calls between frames and/or windows are only allowed if they conform to the same-origin policy. If your window and iframe share a common parent domain you can set document.domain
to "domain lower") one or both such that they can communicate. Otherwise you'll need to look into something like the postMessage() API.
Regarding the error
'CREATE VIEW' must be the first statement in a query batch.
Microsoft SQL Server has a quirky reqirement that CREATE VIEW
be the only statement in a batch. This is also true of a few other statements, such as CREATE FUNCTION
. It is not true of CREATE TABLE
, so go figure …
The solution is to send your script to the server in small batches. One way to do this is to select a single statement and execute it. This is clearly inconvenient.
The more convenient solution is to get the client to send the script in small isolated batches.
The GO
keyword is not strictly an SQL command, which is why you can’t end it with a semicolon like real SQL commands. Instead it is an instruction to the client to break the script at this point and to send the portion as a batch.
As a result, you end up writing something like:
DROP VIEW IF EXISTS … ;
GO
CREATE VIEW … AS … ;
GO
None of the other database servers I have encountered (PostgreSQL, MySQL, Oracle, SQLite) have this quirk, so the requirement appears to be Microsoft Only.
This is quick Bash command, that you're probably searching for, will print only a basename of the remote repository:
Where you fetch from:
basename $(git remote show -n origin | grep Fetch | cut -d: -f2-)
Alternatively where you push to:
basename $(git remote show -n origin | grep Push | cut -d: -f2-)
Especially the -n
option makes the command much quicker.
As lacks suggested send status code in return statement and if you are storing it in some variable like
notfound = 404
invalid = 403
ok = 200
and using
return xyz, notfound
than time make sure its type is int not str. as I faced this small issue also here is list of status code followed globally http://www.w3.org/Protocols/HTTP/HTRESP.html
Hope it helps.
Here is an illustration of your first import cycle problem.
project/controllers/account
^ \
/ \
/ \
/ \/
project/components/mux <--- project/controllers/base
As you can see with my bad ASCII chart is that you are creating an import cycle when project/components/mux
imports project/controllers/account
. Since Go does not support circular dependencies you get the import cycle not allowed
error during compile time.
No need for jQuery! This simple snippet works fine for me. It uses angular.element() to bind window resize event.
/**
* Window resize event handling
*/
angular.element($window).on('resize', function () {
console.log($window.innerWidth);
});
/**
* Window resize unbind event
*/
angular.element($window).off('resize');
Thanks for the answers. Now I know that there are two ways of "SAVE AS" in Vim.
Assumed that I'm editing hello.txt.
Answer by Robert Longson (@RobertLongson) with modifications:
<svg width="100%" height="100%">
<defs>
<filter x="0" y="0" width="1" height="1" id="solid">
<feFlood flood-color="yellow"/>
<feComposite in="SourceGraphic" operator="xor"/>
</filter>
</defs>
<text filter="url(#solid)" x="20" y="50" font-size="50"> solid background </text>
<text x="20" y="50" font-size="50">solid background</text>
</svg>
and we have no bluring and no heavy "getBBox" :) Padding is provided by white spaces in text-element with filter. It's worked for me
Defining an object in Scala is like defining a class in Java that has only static methods. However, in Scala an object can extend another superclass, implement interfaces, and be passed around as though it were an instance of a class. (So it's like the static methods on a class but better).
The feature you're looking for is filter
. It is capable of doing a range of image effects, including brightness:
#myimage {
filter: brightness(50%);
}
You can find a helpful article about it here: http://www.html5rocks.com/en/tutorials/filters/understanding-css/
An another: http://davidwalsh.name/css-filters
And most importantly, the W3C specs: https://dvcs.w3.org/hg/FXTF/raw-file/tip/filters/index.html
Note this is something that's only very recently coming into CSS as a feature. It is available, but a large number of browsers out there won't support it yet, and those that do support it will require a vendor prefix (ie -webkit-filter:
, -moz-filter
, etc).
It is also possible to do filter effects like this using SVG. SVG support for these effects is well established and widely supported (the CSS filter specs have been taken from the existing SVG specs)
Also note that this is not to be confused with the proprietary filter
style available in old versions of IE (although I can predict a problem with the namespace clash when the new style drops its vendor prefix).
If none of that works for you, you could still use the existing opacity
feature, but not the way you're thinking: simply create a new element with a solid dark colour, place it on top of your image, and fade it out using opacity
. The effect will be of the image behind being darkened.
Finally you can check the browser support of filter
here.
Update for RxJS 6 (April 2018)
It is now perfectly fine to import directly from rxjs
. (As can be seen in Angular 6+). Importing from rxjs/operators
is also fine and it is actually no longer possible to import operators globally (one of major reasons for refactoring rxjs 6
and the new approach using pipe
). Thanks to this treeshaking can now be used as well.
Sample code from rxjs repo:
import { Observable, Subject, ReplaySubject, from, of, range } from 'rxjs';
import { map, filter, switchMap } from 'rxjs/operators';
range(1, 200)
.pipe(filter(x => x % 2 === 1), map(x => x + x))
.subscribe(x => console.log(x));
Backwards compatibility for rxjs < 6?
rxjs team released a compatibility package on npm that is pretty much install & play. With this all your rxjs 5.x
code should run without any issues. This is especially useful now when most of the dependencies (i.e. modules for Angular) are not yet updated.
You mention adding the additional include directory (C/C++|General) and additional lib dependency (Linker|Input), but have you also added the additional library directory (Linker|General)?
Including a sample error message might also help people answer the question since it's not even clear if the error is during compilation or linking.
Well, here there's another solution to remove an asociated event (if you already have a method for handling the events for the control):
EventDescriptor ed = TypeDescriptor.GetEvents(this.button1).Find("MouseDown",true);
Delegate delegate = Delegate.CreateDelegate(typeof(EventHandler), this, "button1_MouseDownClicked");
if(ed!=null)
ed.RemoveEventHandler(this.button1, delegate);
Try to declare UseHttpGet over your method.
[ScriptMethod(UseHttpGet = true)]
public string HelloWorld()
{
return "Hello World";
}
In case someone else is brought here by google because they were trying to use a variable for a method within a class, the below is a code sample which will actually work. None of the above worked for my situation. The key difference is the &
in the declaration of $c = & new...
and &$c
being passed in call_user_func
.
My specific case is when implementing someone's code having to do with colors and two member methods lighten()
and darken()
from the csscolor.php class. For whatever reason, I wanted to have the same code be able to call lighten or darken rather than select it out with logic. This may be the result of my stubbornness to not just use if-else or to change the code calling this method.
$lightdark="lighten"; // or optionally can be darken
$color="fcc"; // a hex color
$percent=0.15;
include_once("csscolor.php");
$c = & new CSS_Color($color);
$rtn=call_user_func( array(&$c,$lightdark),$color,$percent);
Note that trying anything with $c->{...}
didn't work. Upon perusing the reader-contributed content at the bottom of php.net's page on call_user_func
, I was able to piece together the above. Also, note that $params
as an array didn't work for me:
// This doesn't work:
$params=Array($color,$percent);
$rtn=call_user_func( array(&$c,$lightdark),$params);
This above attempt would give a warning about the method expecting a 2nd argument (percent).
Combining a variety of elements from the answers here with normalize provides good coverage. Keep the order of operations to incrementally clean the url.
function clean_url(s) {
return s.toString().normalize('NFD').replace(/[\u0300-\u036f]/g, "") //remove diacritics
.toLowerCase()
.replace(/\s+/g, '-') //spaces to dashes
.replace(/&/g, '-and-') //ampersand to and
.replace(/[^\w\-]+/g, '') //remove non-words
.replace(/\-\-+/g, '-') //collapse multiple dashes
.replace(/^-+/, '') //trim starting dash
.replace(/-+$/, ''); //trim ending dash
}
normlize('NFD')
breaks accented characters into their components, which are basic letters plus diacritics (the accent part). replace(/[\u0300-\u036f]/g, "")
purges all the diacritics, leaving the basic letters by themselves. The rest is explained with inline comments.
I used this in my code:
<div class="sticky-top h-100">
<nav id="sidebar" class="vh-100">
....
this cause your sidebar height become 100% and fixed at top.
Usually that problem is that in the last iteration you have an empty object or undefine object. use console.log() inside you cicle to check that this doent happend.
Sometimes a prototype in some place add an extra element.
Since 2017 and Symfony 3.3 you can register Repository as service, with all its advantages it has.
Check my post How to use Repository with Doctrine as Service in Symfony for more general description.
To your specific case, original code with tuning would look like this:
<?php
namespace Test\CommonBundle\Services;
use Doctrine\ORM\EntityManagerInterface;
class UserService
{
private $userRepository;
// use custom repository over direct use of EntityManager
// see step 2
public function __constructor(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
public function getUser($userId)
{
return $this->userRepository->find($userId);
}
}
<?php
namespace Test\CommonBundle\Repository;
use Doctrine\ORM\EntityManagerInterface;
class UserRepository
{
private $repository;
public function __construct(EntityManagerInterface $entityManager)
{
$this->repository = $entityManager->getRepository(UserEntity::class);
}
public function find($userId)
{
return $this->repository->find($userId);
}
}
# app/config/services.yml
services:
_defaults:
autowire: true
Test\CommonBundle\:
resource: ../../Test/CommonBundle
The original poster states:
The best answer someone could give me was to use
git revert
X times until I reach the desired commit.So let's say I want to revert back to a commit that's 20 commits old, I'd have to run it 20 times.
Is there an easier way to do this?
I can't use reset cause this repo is public.
It's not necessary to use git revert
X times. git revert
can accept a
commit range as an argument, so you only need to use it once to revert a range
of commits. For example, if you want to revert the last 20 commits:
git revert --no-edit HEAD~20..
The commit range HEAD~20..
is short for HEAD~20..HEAD
, and means "start from the 20th parent of the HEAD commit, and revert all commits after it up to HEAD".
That will revert that last 20 commits, assuming that none of those are merge commits. If there are merge commits, then you cannot revert them all in one command, you'll need to revert them individually with
git revert -m 1 <merge-commit>
Note also that I've tested using a range with git revert
using git version 1.9.0. If you're using an older version of git, using a range with git revert
may or may not work.
In this case, git revert
is preferred over git checkout
.
Note that unlike this answer that says to use git checkout
, git revert
will actually remove any files that were added in any of the commits that you're
reverting, which makes this the correct way to revert a range of revisions.
What I have found is that simply wrapping code in the componentDidMount
or componentDidUpdate
with a setTimeout
with a time of 0 milliseconds ensures that the browser DOM has been updated with the React changes before executing the setTimeout
function.
Like this:
componentDidMount() {
setTimeout(() => {
$("myclass") // $ is available here
}, 0)
}
This puts the anonymous function on the JS Event Queue to run immediately after the currently running React stack frame has completed.
Or you can cast your string to Date format with date function. Even the date is stored as TEXT in the DB. Like this (the most workable variant):
SELECT * FROM test WHERE date(date)
BETWEEN date('2011-01-11') AND date('2011-8-11')
It looks like you are interesting in performing an operation everything for a given year, if this is indeed the case, I would recommend to use the YEAR() function like this:
SELECT * FROM `table` WHERE YEAR(date_column) = '2012';
The same goes for DAY() and MONTH(). They are also available for MySQL/MariaDB variants and was introduced in SQL Server 2008 (so not for specific 2000).
You seem to have the quote marks ("
) embedded in your string at the start and the end. These are not needed and are illegal characters in a path. How are you initializing the string with the path?
This can be seen from the debugger visualizer, as the string starts with "\"
and ends with \""
, it shows that the quotes are part of the string, when they shouldn't be.
You can do two thing - a regular escaped string (using \
) or a verbatim string literal (that starts with a @
):
string str = "C:\\Program Files (x86)\\test software\\myapp\\demo.exe";
Or:
string verbatim = @"C:\Program Files (x86)\test software\myapp\demo.exe";
I had the same problem when switching from absolute to relative path for my xml file. The following solves both loading and using relative source path issues. Using a XmlDataProvider, which is defined in xaml (should be possible in code too) :
<Window.Resources>
<XmlDataProvider
x:Name="myDP"
x:Key="MyData"
Source=""
XPath="/RootElement/Element"
IsAsynchronous="False"
IsInitialLoadEnabled="True"
debug:PresentationTraceSources.TraceLevel="High" /> </Window.Resources>
The data provider automatically loads the document once the source is set. Here's the code :
m_DataProvider = this.FindResource("MyData") as XmlDataProvider;
FileInfo file = new FileInfo("MyXmlFile.xml");
m_DataProvider.Document = new XmlDocument();
m_DataProvider.Source = new Uri(file.FullName);
The IFormatProvider
interface is normally implemented for you by a CultureInfo
class, e.g.:
CultureInfo.CurrentCulture
CultureInfo.CurrentUICulture
CultureInfo.InvariantCulture
CultureInfo.CreateSpecificCulture("de-CA") //German (Canada)
The interface is a gateway for a function to get a set of culture-specific data from a culture. The two commonly available culture objects that an IFormatProvider
can be queried for are:
The way it would normally work is you ask the IFormatProvider
to give you a DateTimeFormatInfo
object:
DateTimeFormatInfo format;
format = (DateTimeFormatInfo)provider.GetFormat(typeof(DateTimeFormatInfo));
if (format != null)
DoStuffWithDatesOrTimes(format);
There's also inside knowledge that any IFormatProvider
interface is likely being implemented by a class that descends from CultureInfo
, or descends from DateTimeFormatInfo
, so you could cast the interface directly:
CultureInfo info = provider as CultureInfo;
if (info != null)
format = info.DateTimeInfo;
else
{
DateTimeFormatInfo dtfi = provider as DateTimeFormatInfo;
if (dtfi != null)
format = dtfi;
else
format = (DateTimeFormatInfo)provider.GetFormat(typeof(DateTimeFormatInfo));
}
if (format != null)
DoStuffWithDatesOrTimes(format);
All that hard work has already been written for you:
To get a DateTimeFormatInfo
from an IFormatProvider
:
DateTimeFormatInfo format = DateTimeFormatInfo.GetInstance(provider);
To get a NumberFormatInfo
from an IFormatProvider
:
NumberFormatInfo format = NumberFormatInfo.GetInstance(provider);
The value of IFormatProvider
is that you create your own culture objects. As long as they implement IFormatProvider
, and return objects they're asked for, you can bypass the built-in cultures.
You can also use IFormatProvider
for a way of passing arbitrary culture objects - through the IFormatProvider
. E.g. the name of god in different cultures
This lets your custom LordsNameFormatInfo
class ride along inside an IFormatProvider
, and you can preserve the idiom.
In reality you will never need to call GetFormat
method of IFormatProvider
yourself.
Whenever you need an IFormatProvider
you can pass a CultureInfo
object:
DateTime.Now.ToString(CultureInfo.CurrentCulture);
endTime.ToString(CultureInfo.InvariantCulture);
transactionID.toString(CultureInfo.CreateSpecificCulture("qps-ploc"));
Note: Any code is released into the public domain. No attribution required.
I believe that main()
should return either EXIT_SUCCESS
or EXIT_FAILURE
. They are defined in stdlib.h
Try the -Force
parameter:
New-Item -ItemType Directory -Force -Path C:\Path\That\May\Or\May\Not\Exist
You can use Test-Path -PathType Container
to check first.
See the New-Item MSDN help article for more details.
You simply need to create an instance of ReportHandler:
ReportHandler rh = new ReportHandler(/* constructor args here */);
rh.executeBatchInsert(); // Having fixed name to follow conventions
The important point of instance methods is that they're meant to be specific to a particular instance of the class... so you'll need to create an instance first. That way the instance will have access to the right connection and prepared statement in your case. Just calling ReportHandler.executeBatchInsert
, there isn't enough context.
It's really important that you understand that:
Once you understand that fundamental difference, it makes sense that you can't call an instance method without creating an instance... For example, it makes sense to ask, "What is the height of that person?" (for a specific person) but it doesn't make sense to ask, "What is the height of Person?" (without specifying a person).
Assuming you're leaning Java from a book or tutorial, you should read up on more examples of static and non-static methods etc - it's a vital distinction to understand, and you'll have all kinds of problems until you've understood it.
This is not a code issue. It is your default IE settings
To change the "always open" setting:
EDIT: If you ask me , instead of making any changes in the code i would add the following text "Internet Explorer users: To download file, "Rightclick" the link and hit "Save target as" to download the file."
EDIT 2: THIS solution will work perfectly for you. Its a solution i just copied from the other answer. Im not trying to pass it off as my own
Content-Type: application/octet-stream
Content-Disposition: attachment;filename=\"filename.xxx\"
However you must make sure that you specify the type of file(s) you allow. You have mentioned in your post that you want this for any type of file. This will be an issue.
For ex. If your site has images and if the end user clicks these images then they will be downloaded on his computer instead of opening in a new page. Got the point. So you need to specify the file extensions.
session_start();
echo '<pre>';var_dump($_SESSION);echo '</pre>';
// or
echo '<pre>';print_r($_SESSION);echo '</pre>';
NOTE: session_start(); line is must then only you will able to print the value $_SESSION
The first one is the default object constructor call. You can use it's parameters if you want.
var array = new Array(5); //initialize with default length 5
The second one gives you the ability to create not empty array:
var array = [1, 2, 3]; // this array will contain numbers 1, 2, 3.
Simple JPA update..
Customer customer = em.find(id, Customer.class); //Consider em as JPA EntityManager
customer.setName(customerDto.getName);
em.merge(customer);
Define this in your String.xml file and name the array what you want, such as "Weight"
<string-array name="Weight">
<item>Kg</item>
<item>Gram</item>
<item>Tons</item>
</string-array>
and this code in your layout.xml
<Spinner
android:id="@+id/fromspin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:entries="@array/Weight"
/>
In your java file, getActivity
is used in fragment; if you write that code in activity, then remove getActivity
.
a = (Spinner) findViewById(R.id.fromspin);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),
R.array.weight, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
a.setAdapter(adapter);
a.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (a.getSelectedItem().toString().trim().equals("Kilogram")) {
if (!b.getText().toString().isEmpty()) {
float value1 = Float.parseFloat(b.getText().toString());
float kg = value1;
c.setText(Float.toString(kg));
float gram = value1 * 1000;
d.setText(Float.toString(gram));
float carat = value1 * 5000;
e.setText(Float.toString(carat));
float ton = value1 / 908;
f.setText(Float.toString(ton));
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
});
// Inflate the layout for this fragment
return v;
}
David, Error comes Microsoft Office Excel has stopped working. Two options check online for a solution and close the programme and other option Close the program I am sure error is in my array but I am reading everything and seem this is way to define arrays.
Rule number one of interviews; never say impossible.
No need for hidden character trickery.
window.__defineGetter__( 'a', function(){_x000D_
if( typeof i !== 'number' ){_x000D_
// define i in the global namespace so that it's not lost after this function runs_x000D_
i = 0;_x000D_
}_x000D_
return ++i;_x000D_
});_x000D_
_x000D_
if( a == 1 && a == 2 && a == 3 ){_x000D_
alert( 'Oh dear, what have we done?' );_x000D_
}
_x000D_
This can be caused if the client is in a different domain than the server.
I encountered this when testing one of my applications from my PC(client) to my (cloud) testing server and the simplest solution i could think of was setting up a vpn.
The version of the errorHandler middleware bundled with some (perhaps older?) versions of express seems to have the status code hardcoded. The version documented here: http://www.senchalabs.org/connect/errorHandler.html on the other hand lets you do what you are trying to do. So, perhaps trying upgrading to the latest version of express/connect.
Don't forget to take into consideration the global flag in your regexp :
var reg = /abc/g;
!!'abcdefghi'.match(reg); // => true
!!'abcdefghi'.match(reg); // => true
reg.test('abcdefghi'); // => true
reg.test('abcdefghi'); // => false <=
This is because Regexp keeps track of the lastIndex when a new match is found.
The funny thing is: I host projects in Subversion Repos, but access them via the Git Clone command.
Please read Develop with Git on a Google Code Project
Although Google Code natively speaks Subversion, you can easily use Git during development. Searching for "git svn" suggests this practice is widespread, and we too encourage you to experiment with it.
Using Git on a Svn Repository gives me benefits:
backup/public
svn repository for others to check outFor frequent uses of this command I found it easy to add the location of C:\xampp\apache\bin
to the PATH
. Use whatever directory you have this installed in.
Then you can run from any directory in command line:
httpd -k restart
The answer above that suggests httpd -k -restart is actually a typo. You can see the commands by running httpd /?