Id
int64
2.49k
75.6M
PostTypeId
int64
1
1
AcceptedAnswerId
int64
2.5k
75.6M
Question
stringlengths
7
28.7k
Answer
stringlengths
0
24.3k
Image
imagewidth (px)
1
10k
18,712,258
1
18,723,628
I have a strange problem in IE7. I have position absolute div insde each list item. But the absolute div is hiding inside the div in IE7. The last div seems OK. <IMAGE> JSFIDDLE: <URL> ''' <div class="listitem"> Some long content here bl a bla blaaaaaaa baaaaaaaaaaa <div class="layer">I'm a layer</div> </div> <div class="listitem"> Some long content here bl a bla blaaaaaaa baaaaaaaaaaa <div class="layer">I'm a layer</div> </div> <div class="listitem"> Some long content here bl a bla blaaaaaaa baaaaaaaaaaa <div class="layer">I'm a layer</div> </div> <div class="listitem"> Some long content here bl a bla blaaaaaaa baaaaaaaaaaa <div class="layer">I'm a layer</div> </div> <div class="listitem"> Some long content here bl a bla blaaaaaaa baaaaaaaaaaa <div class="layer">I'm a layer</div> </div> <div class="listitem"> Some long content here bl a bla blaaaaaaa baaaaaaaaaaa <div class="layer">I'm a layer</div> </div> <div class="listitem"> Some long content here bl a bla blaaaaaaa baaaaaaaaaaa <div class="layer">I'm a layer</div> </div> ''' ''' .container { width:900px; margin:0 auto; } .listitem { position:relative; background:#00CC00; border-bottom:1px solid #FFF; min-height:30px; } .layer { position:absolute; top:10px; right:10px; padding:10px; background:#993300; border:solid 1px #FFF; z-index:100; overflow:visible; } ''' Any Idea how to to fix this issue in IE7? Thanks in advance.
## Add a wrapper element <URL> If editing the HTML source code is an option, add a wrapper element around the side content, and place it before the main text content. Then add 'position:relative' to the wrapper element rather than adding it to '.listitem'. This moves the local stacking context (created at an inconvenient time in IE7) to an element where it does no harm. ''' <div class="container"> <div class="listitem"> <div class="wrapper"> <div class="layer">I'm a layer</div> </div> Some long content here bla bla blaaaaaaa baaaaaaaaaaa </div> .... </div> ''' ''' .listitem { /* position: relative; */ /* Removed here */ .... } .wrapper { position: relative; /* Added here */ height: 0; } ''' ## jQuery If editing the HTML source code isn't an option, there are a few options available using jQuery. 1. Take the basic approach presented by @avrahamcool (setting the z-index of each .listitem to a decreasingly small value). The downside to this approach is that it reverses the layering order of the side elements relative to one another, which may or may not be acceptable. 2. Use jQuery to edit the HTML DOM so that the HTML is as shown above, using the related CSS changes as well. The downside to this approach is that the styling of the content won't render correctly until after the jQuery code has run. So the content may briefly appear broken when the page first loads. 3. Set .container to position:relative, rather than .listitem. Use jQuery to calculate the relative position of each of .listitem element within .container, and set the top position of each side element based on this. This approach has the same downside as solution #2. 4. In an extreme case, if even editing the JavaScript isn't an option, you could simulate solution #1 by adding a series of increasingly long CSS selectors with decreasing z-index values (as shown below). I don't recommend this approach, as it's wildly impractical, but it could be used as a last resort. ''' .listitem {z-index:99;} .listitem + .listitem {z-index:98;} .listitem + .listitem + .listitem {z-index:97;} ... ''' ## Conclusion In short, the current HTML doesn't support this type of layout in IE7. The only elegant solution is to change the HTML source code to something that does support it. Any jQuery solution will tend to be awkward in one way or another.
15,940,601
1
15,940,696
Basically I want a user to be able to create a list that looks something like this: ''' Please give me all books by: James Arnold Tom Seaver ''' I only need line breaks preserved... My code is giving me a problem: When I save the information into the database, the formatting is being preserved, but when I put the information into the textarea, there are a lot of extra spaces. I have attached a picture so you can see what it looks like. ''' <?php session_start(); if (!isset($_SESSION['user'])) header('Location: ../index.php'); require ("../login.php"); include ("header.php"); include ("subnav.php"); $user_id = $_SESSION['user']; $form_show = true; if (isset($_POST['submit'])) { if (empty($_POST['notes'])) { $stmt = $db->prepare("SELECT * FROM notes WHERE user=:id"); $stmt->bindValue(':id', $user_id, PDO::PARAM_INT); $stmt->execute(); $rows = $stmt->fetchAll(); $num_rows = count($rows); if ($num_rows == 0) { $form_show = false; $errors[] = 'You do not currently have any notes to edit, therefore nothing to delete!.'; } else { $stmt = $db->prepare("DELETE FROM notes WHERE user=:id"); $stmt->bindValue(':id', $user_id, PDO::PARAM_INT); $stmt->execute(); $errors[] = 'Your notes have been successfully deleted.'; $form_show = false; } } else { $stmt = $db->prepare("SELECT * FROM notes WHERE user=:id"); $stmt->bindValue(':id', $user_id, PDO::PARAM_INT); $stmt->execute(); $rows = $stmt->fetchAll(); $num_rows = count($rows); if ($num_rows == 0) { $stmt = $db->prepare("INSERT INTO notes (user, notes) VALUES (:user, :notes)"); $stmt->bindValue(':user', $user_id, PDO::PARAM_INT); $stmt->bindValue(':notes', trim($_POST['notes']), PDO::PARAM_STR); $stmt->execute(); echo 'Your notes have been successfully added!'; $form_show = false; } else { $stmt = $db->prepare("UPDATE notes SET notes=:notes WHERE user=:id"); $stmt->bindValue(':notes',trim($_POST['notes']), PDO::PARAM_STR); $stmt->bindValue(':id', $user_id, PDO::PARAM_INT); $stmt->execute(); echo 'Your notes have been successfully updated!'; $form_show = false; } } } ?> <?php if (!empty($errors)) foreach($errors as $error) echo $error; ?> <?php if ($form_show == true) { ?> <p>Use this page to add any notes you would like to list for your subscription. For example, if you want all books by a particular artist, here is the place to add that information!</p> <form action="" method="post"> <ul> <li> Notes: <br> <textarea name="notes" rows="30" cols="70"> <?php $stmt = $db->prepare("SELECT * FROM notes WHERE user=:id"); $stmt->bindValue(':id', $user_id, PDO::PARAM_INT); $stmt->execute(); $rows = $stmt->fetchAll(); $num_rows = count($rows); if ($num_rows != 0) foreach ($rows as $row) echo $row['notes']; ?> </textarea> </li> <li> <input type="submit" value="Modify Notes" name ="submit" id="submit"> </li> </ul> </form> <?php } ?> <?php include ("footer.php"); ?> ''' Here is a picture: <IMAGE>
Shouldn't the following query: ''' "UPDATE notes SET notes=:notes WHERE id=:id" ''' be: ''' "UPDATE notes SET notes=:notes WHERE user=:id" ''' For the second one, you can try replacing 'nl2br($_POST['notes'])' with ''' nl2br( trim($_POST['notes']) ) ''' I still don't understand what the second question is? --- The second problem is generated because of the available empty spaces inside your text-area. The following looks ugly, but will provide you with what you desire. ''' <textarea name="notes" rows="30" cols="70"><?php $stmt=$ db->prepare("SELECT * FROM notes WHERE user=:id"); $stmt->bindValue(':id', $user_id, PDO::PARAM_INT); $stmt->execute(); $rows = $stmt->fetchAll(); $num_rows = count($rows); if ($num_rows != 0) foreach ($rows as $row) echo $row['notes']; ?></textarea> '''
11,703,685
1
11,710,441
I've been trying for hours now, but I have no idea what is wrong. Normally, when you define a public object/var in Unity C#, it shows up in the inspector or default references where you can drag something to it. Here's my test code: ''' using UnityEngine; using System; using System.Collections; [Serializable] public class modGlobals : MonoBehaviour { public static GUIStyle defaultMask; public GUIStyle trollo; } ''' Aaaaaand... <IMAGE> I tried several options, wrote the thing in MonoDev as also in Visual Studio, put all my files in an namespace, w and w/o Serializable attribe but.. What could be wrong? Thanks for help!
Yes you do need to attach it to a gameObject in the scene in order to show the public members in the property inspector, since your script inherits from MonoBehaviour. This is what I got. <IMAGE> Additionally, you cannot expose static members in the property inspector - even when marked as SerializableAttribute. System.SerializableAttribute is not valid on this declaration type. It is valid on 'class, struct, enum, delegate' declarations only. In relation to your comment about requiring a globally accessible script with objects, you have a couple options, such as - <URL>-
60,981,735
1
60,981,984
Well, I have this a similar question to <URL>. Now I get this problem in VS Code despites I have my session instantiation on my server. ### The problem <IMAGE> ### The instantiation ''' // Middlewares app.use(bodyParser.urlencoded({ extended: false })); app.use(logger(process.env.NODE_ENV === 'development' ? 'dev' : 'combined')); app.use(express.json()); app.use(session({ secret: process.env.NODE_ENV === 'development' ? process.env.SESSION_SECRET : 'secret', resave: false, saveUninitialized: true })); app.use(passport.initialize()); app.use(passport.session()); ''' No errors above. Therefore... the app in fact works... but I get this "error color" on my VSC file that would be great to avoid. Any suggestions? Just in case, I will include the whole router file: ''' // POST - Crear usuario router.post('/', async (req: Request, res: Response) => { const resultado: IResultado = { data: null, ok: false }; const messages: Array<object> = []; const datos: IUsuario = req.body; // Validacion de campos if (!validator.isEmail(datos.email)) { messages.push({ email: 'El correo electronico es invalido'}); } if (validator.isLength(datos.password, { max: 5})) { messages.push({ password: 'La contrasena debe tener como minimo seis caracteres' }); } if (!validator.isMobilePhone(datos.telefono, ['es-UY'])) { messages.push({ telefono: 'El numero de telefono es invalido' }); } if (!empty(messages)) { resultado.message = 'No se pudo crear el usuario'; resultado.messages = messages; return res.json(resultado); } datos.password = await bcrypt.hash(datos.password, 10); datos.fechaCreacion = Date.now(); datos.fechaActualizacion = Date.now(); if (req.user && req.user) { datos.propietario = req.user.email; } const ref: any = db.collection('usuarios').doc(datos.email); const doc = await ref.get(); if (doc.exists) { // Usuario ya existe resultado.message = 'El correo electronico ya esta en uso'; return res.json(resultado); } try { await ref.set(datos); delete datos.password; resultado.message = 'Usuario creado correctamente'; resultado.data = datos; resultado.ok = true; return res.json(resultado); } catch(error) { resultado.message = 'No se pudo crear el usuario'; resultado.error = error; console.log(error); return res.status(500).json(resultado); } }); ''' ### The User interface (@types/passport module) ''' // tslint:disable-next-line:no-empty-interface interface AuthInfo {} // tslint:disable-next-line:no-empty-interface interface User {} interface Request { authInfo?: AuthInfo; user?: User; ... '''
You need to extend the 'Express.User' type: ''' declare global { namespace Express { interface User { email: string; } } } '''
4,504,854
1
4,554,490
# Hi, ## I am using the following javascript... ''' g_viewInfo.drawContext.projection = g_math.matrix4.perspective( g_math.degToRad(30), // 30 degree fov. g_client.width / g_client.height, 1, // Near plane. 9999); // Far plane. ''' Can anyone tell me what the maximum far plane of an o3d (webgl) projection is? I have tried using 5000 and 9999 but everything still seems to disappear at the same point. I have tried to locate this information in the SDK's current documentation. Is there a reason for such a weak limitation? Is it possible to hack the max value? <IMAGE>
Played with the near plane in conjunction with the far plane and got the distancing problems sorted
17,241,547
1
17,242,167
I have a table that has 14 columns in it. These columns are color, type, ft, date, count, etc. What I need is to select all distinct records of id and type with the most recent date. So, for example... color------type-----------date red--------work-----------01/01/01 red---------play----------02/02/02 red---------play----------03/03/03 In this case, I want to return red, work, 01/01/01 and red, play 03/03/03. Hopefully this makes sense. I've tried different combinations of select unique and select distinct and group bys, and I haven't been able to come up with anything. Here is the SQL statement I'm trying: ''' select distinct chock_id, roll_type, max(chock_service_dt), chock_id_dt, chock_seq_num, chock_service_cmnt, total_rolled_lineal_ft, total_rolled_tons, chock_usage_cnt, chock_insert_dt, record_modify_dt, next_chock_service_dt_act, previous_alarm_value, upload_complete_yn from tp07_chock_summary_row group by chock_id, roll_type, chock_service_dt, chock_id_dt, chock_seq_num, chock_service_cmnt, total_rolled_lineal_ft, total_rolled_tons, chock_usage_cnt, chock_insert_dt, record_modify_dt, next_chock_service_dt_act, previous_alarm_value, upload_complete_yn; ''' <IMAGE> Here's a screenshot. Like I said in a comment below, like in rows 2 and 4, I can't have multiple records with the same chock_id and roll_type.
Given your new requirements, which you did not explain initially, this should do it: ''' select chock_id, roll_type, chock_service_dt, chock_id_dt, chock_seq_num, chock_service_cmnt, total_rolled_lineal_ft, total_rolled_tons, chock_usage_cnt, chock_insert_dt, record_modify_dt, next_chock_service_dt_act, previous_alarm_value, upload_complete_yn from ( select chock_id, roll_type, chock_service_dt, chock_id_dt, chock_seq_num, chock_service_cmnt, total_rolled_lineal_ft, total_rolled_tons, chock_usage_cnt, chock_insert_dt, record_modify_dt, next_chock_service_dt_act, previous_alarm_value, upload_complete_yn, row_number() over ( partition by chock_id, roll_type order by chock_service_dt desc ) rn from tp07_chock_summary_row ) where rn = 1 '''
17,803,089
1
17,804,393
I have created a GCM Intent service and the device is getting registered successfully. I also receive the REGISTRATION Intent, but the OnMessage or OnRegistered methods are not getting called. Below the log i see. ''' 07-23 06:24:23.542: V/GCMBroadcastReceiver(1168): onReceive: com.google.android.c2dm.intent.REGISTRATION 07-23 06:24:23.542: V/GCMBroadcastReceiver(1168): GCM IntentService class: com.app.demo.myApp.GCMIntentService 07-23 06:24:23.581: V/GCMBaseIntentService(1168): Acquiring wakelock ''' Below is the code for OnMessage. Could someone pls help me as to why the OnRegistered or OnMessage is not getting called. ''' public class GCMIntentService extends GCMBaseIntentService { @Override protected void onMessage(Context arg0, Intent arg1) { // TODO Auto-generated method stub Toast.makeText(getApplicationContext(), "registered", Toast.LENGTH_LONG).show(); String device_id = GCMRegistrar.getRegistrationId(this); GSLogger.Log("mess_received", device_id); } @Override protected void onRegistered(Context context, String arg1) { Toast.makeText(context, "registered", Toast.LENGTH_LONG).show(); String device_id = GCMRegistrar.getRegistrationId(this); GSLogger.Log("registered", device_id); } } ''' Manifest Code: ''' <uses-sdk android:minSdkVersion="7" android:targetSdkVersion="8" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.READ_CALENDAR" /> <uses-configuration android:name="android.permission.GET_ACCOUNTS"/> <uses-permission android:name="com.google.android.c2dm.permission.C2D_MESSAGE"/> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> <permission android:name="com.app.demo.myApp.permission.C2D_MESSAGE" android:protectionLevel="signature" /> <uses-permission android:name="com.app.demo.myApp.permission.C2D_MESSAGE" /> ''' Receiver Code in Manifest: ''' <receiver android:name="com.google.android.gcm.GCMBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" > <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> <action android:name="com.google.android.c2dm.intent.REGISTRATION" /> <category android:name="com.app.demo.myApp" /> </intent-filter> </receiver> <service android:name="com.app.demo.myApp.GCMIntentService" /> ''' Pic of My Package: <IMAGE>
The issue is ''' <service android:name="com.app.demo.myApp.GCMIntentService" /> ''' Just give ''' <service android:name=".GCMIntentService" /> ''' And place your GCMIntentService Java file in the folder as specified by your package name in manifest. For example if you have declared com.app.demo.myApp as the application package name Place your GCMIntentService in the same folder structure.
23,799,062
1
23,809,312
Have written a code for toggling months and years like you see in the windows clock when you click on it on right bottom corner. I just want to achieve the upper part highlighted in red. No calender under it. <IMAGE> I have achieved all of it but there is glitch. When you go to the future months it changes the year in December. It should change the year on January. Same with when you go back. You can see live example here... <URL> Here is my jQuery Code: ''' var $months = [ "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var d = new Date(); var $m = d.getMonth() + 1; var $y = d.getFullYear(); $('.history-months').click(function () { var month_num = $('.months').attr('month-count'); var year_num = $('.years').text(); var history_month = parseFloat(month_num) - 1; $('.months').attr("month-count", history_month); $('.months').text($months[history_month]); if (month_num < 3) { $('.months').attr("month-count", 13); var history_year = parseFloat(year_num) - 1; $('.years').text(history_year); } }); $('.future-months').click(function () { var month_num = $('.months').attr('month-count'); var year_num = $('.years').text(); var future_month = parseFloat(month_num) + 1; $('.months').attr("month-count", future_month); $('.months').text($months[future_month]); if (month_num > 10) { $('.months').attr("month-count", 0); var history_year = parseFloat(year_num) + 1; $('.years').text(history_year); } }); $('.months').text($months[$m]).attr('month-count', $m); $('.years').text($y); ''' and here is the HTML: ''' <a href="#" class="history-months">&LT;</a> <span class="months-years"> <span class="months"></span> <span class="years"></span> </span> <a href="#" class="future-months">&GT;</a> ''' Any ideas? Thanks Omer
Ok found the solution myself :p I thought i should share with the world as well :) Just edit my condition a bit: ''' $('.future-months').click(function() { var month_num = $('.months').attr('month-count'); var year_num = $('.years').text(); var future_month = parseFloat(month_num) + 1; if (future_month > 12) { future_month = 1; year_num = parseFloat(year_num) + 1; } $('.months').attr("month-count", future_month); $('.months').text($months[future_month]); $('.years').text(year_num); }); $('.history-months').click(function() { var month_num = $('.months').attr('month-count'); var year_num = $('.years').text(); var history_month = parseFloat(month_num) - 1; if (history_month < 1) { history_month = 12; year_num = parseFloat(year_num) - 1; } $('.months').attr("month-count", history_month); $('.months').text($months[history_month]); $('.years').text(year_num); }); ''' Hope it will be helpful for others :) Omer
25,750,456
1
26,265,583
Some ASP.NET controls have properties that allow you to browse for a URL like so: <IMAGE> How do I do that? This is my property so far: ''' [Category("Video Attributes")] [Editor("System.Web.UI.Design.UrlEditor", typeof(System.Drawing.Design.UITypeEditor))] public Uri VideoLocation { get { return _vidLocation; } set { _vidLocation = value; } } ''' I can see and edit the property and if I type a URL myself, it works. But it sure would make life easier if I could browse for the URL. Better still would be if it could default to a specific folder. Thanks in advance for your help!
I figured it out. Just going to wrap up this question with example code ''' private String _tutorialFile = ""; ''' ... ''' [Category("Linked Files")] [UrlProperty(), Editor(typeof(System.Web.UI.Design.UrlEditor), typeof(System.Drawing.Design.UITypeEditor))] public String TutorialFile { get; set; } '''
9,064,787
1
9,065,619
I'm using CorePlot to draw PieChart. I would like to display labels for slices on slices themselves. Is there a way to get coordinates of each slice and then setting the frame of CPTLayer that holds the text label to adjust to coordinates of the slice? What I am doing so far: ''' -(CPRLayer*) datLabelForPlot(CPTPlot*)plot recordIndex:(NSUInteger)index { static CPTMutableTextStyle *textStyle = nil; NSString *string = @"Test"; if ( !textStyle) { textStyle= [[CPTMutableTextStyle alloc] init]; textStyle.color = [CPTColor whiteColor]; } CPTLayer *layer = [[[CPTLayer alloc] initWithFrame:CGRectMake(50,50, 100, 20)]autorelease]; CPTTextLayer *newLayer = nil; newLayer = [[[CPTTextLayer alloc] initWithText:string style:textStyle] autorelease]; [layer addSublayer:newLayer]; return layer; } ''' but regardless of the layer frame, label is always displayed at the same position (outside the chart). How to set the appropriate layer frame to display the text on the slice itself? Here is the image of the points I would like to know: <IMAGE>
Have you tried setting the 'CPPieChart labelOffset' property to a negative value? May be it doesn't provide the level of precision that you need, but it's an easy solution. Positive Offset: <IMAGE> Negative Offset: <IMAGE>
8,711,952
1
8,712,074
hello i wanted to build I get $date and $date1 from form xxx. I wanted to make leave program. now i wanted process $date with variable string with value xx-xx-xxxx(dd/mm/yyyy)and $date1 with value now i want to convert them to date. I already know how to count day using datediff() i convert $date so i can use dateadd() function Here the code ''' $t1 = substr($date,0,2); $b1 = substr($date,3,2); $y1 = substr($date,6,4); $t2 = substr($date11,0,2); $b2 = substr($date1,3,2); $y2 = substr($date1,6,4); $tawal ="$y1-$b1-$t1"; $takhir = "$y2-$b2-$t2"; $query = "SELECT datediff('$takhir', '$tawal')as selisih"; $hasil = mysql_query($query); $data = mysql_fetch_array($hasil); $times = $data['selisih']; $times = + 1; ''' here the picture <IMAGE>
You don't need substr or mysql for this. First get your dates without substr: ''' $tawal = date('Y-m-d', strtotime($date)); $takhir = date('Y-m-d', strtotime($date1)); ''' Now you have the Y-m-d formatted strings. To find the diff, though you don't have to convert to Y-m-d since we don't need mysql. You can use <URL> to find the difference in seconds. ''' $diff = abs(strtotime($date2) - strtotime($date)); $years = floor($diff / (365*60*60*24)); $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24)); $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24)); '''
60,012,404
1
60,012,542
I am trying to color my lines in ggplot to be red and blue, but they seem to have reversed colors. ''' ggplot(data.frame(x)) + geom_line(aes(x=x, y=y, color='blue')) + geom_line(aes(x=x, y=y2, color='red')) + labs(title ="Normal Distribution Curve & Normal CDF Curve ") ''' To that end, how can I override the text in the legend to not say "red" and "blue" but instead be labeled "distribution 1" and "distribution 2"? <IMAGE>
You can repeat your x values twice, and put them under the same data frame with y1 and y2, this is the long format: ''' x = seq(-5,5,by=0.1) y = dnorm(x,0,1) y2 = dnorm(x,1,0.25) dat = data.frame( x = rep(x,2), y = c(y,y2), type = rep(c("distribution 1","distribution 2"),each=length(x)) ) ggplot(dat,aes(x=x,y=y,color=type)) + geom_line() + scale_color_manual(values=c("blue","red"))+ labs(title ="Normal Distribution Curve & Normal CDF Curve ") ''' <URL>
6,281,002
1
6,282,446
i am trying to get an image border sliced for use in css. ## Here is the Box borders i want to use: <IMAGE> ## Here is part of the code for the Box: ''' <div class="wrapper"> <div id="featured_box1"> <div class="Content1"> <h2>Heading</h2> <p>Content for Featured Box</p> </div> </div> </div> ''' How should i slice the images, should i slive a small area and then repeat-y for each side. and then create 4 new divs to insert the corners of the border ? So how to handle the corners of the borders ? Which is the best way to get the box displayed with fasting loading speed?
> @thirtydot, The box width is fixed, both width and height. How do I use 4 corners with divs ? - Ibn Saeed Maybe I'm missing something, but if the box is a fixed size, can't you just set the 'width' and 'height' of your 'div' to the exact dimensions, and set it as a 'background-image'? Like this: <URL>
23,351,137
1
23,351,255
I'm making an application and I require some help please. In flash, gameLoops can be either made with an enterFrame, or timer. I am new to Java so please forgive me arrogance. From researching I've seen people using timers. Now I Have a tile based game, where if the user clicks on a grid (It's 30*21) the player will go to that grid. Here is what I've come up with ''' for(int i = 0; i<30; i++) { for(int j = 0; j<21; j++) { if(e.getSource()==JbGrid[i][j]) { MOUSE_X = j; MOUSE_Y = i; System.out.println("Mouse X: "+MOUSE_X+" Mouse Y: "+MOUSE_Y); moveToSquare(); } } } } public void moveToSquare() { if( BPOS_X < MOUSE_X ) { BPOS_X +=2; } if( BPOS_X > MOUSE_X ) { BPOS_X -=2; } } ''' Now the problem is that the game doesn't physically show the red block moving towards the MOUSE_X position, this is because the page isn't being refreshed. Is there a way I can implement a gameLoop in to my code. It's just that most people implement it at the start, and I never knew about "gameLoops" before I started my project. Can someone please point my in the right direction ''' if(player clicks square) activate loop move player to Mouse_X ''' Thank you. <IMAGE>
It looks like you're using Swing, and if your question is how to get a game loop out of an application using the basics of Swing (an application not using BufferStrategy, but a combination of different Swing components), then you roughly want the following: - - - The custom JComponent you create can have listeners on various buttons or other things such as mouse clicks, where you can use the same reference to the game state object you use to draw to update the game's state based on the UI actions. Make sure your code is thread safe too as the repaint executing on the EDT, or one of your Swing listeners, can occur at the same time you update your state with the Timer object. If you search online for example usage of game loops in Java using BufferStrategy you'll find more traditional game loop examples.
16,368,989
1
16,369,524
I draw a graph but unfortunately my legend falls out of the figure. How can I correct it? I put a dummy code to illustrate it: <IMAGE> ''' from matplotlib import pyplot as plt from bisect import bisect_left,bisect_right import numpy as np global ranOnce ranOnce=False def threeLines(x): """Draws a function which is a combination of two lines intersecting in a point one with a large slope and one with a small slope. """ start=0 mid=5 end=20 global ranOnce,slopes,intervals,intercepts; if(not ranOnce): slopes=np.array([5,0.2,1]); intervals=[start,mid,end] intercepts=[start,(mid-start)*slopes[0]+start,(end-mid)*slopes[1]+(mid-start)*slopes[0]+start] ranOnce=True; place=bisect_left(intervals,x) if place==0: y=(x-intervals[place])*slopes[place]+intercepts[place]; else: y=(x-intervals[place-1])*slopes[place-1]+intercepts[place-1]; return y; def threeLinesDrawer(minimum,maximum): t=np.arange(minimum,maximum,1) fig=plt.subplot(111) markerSize=400; fig.scatter([minimum,maximum],[threeLines(minimum),threeLines(maximum)],marker='+',s=markerSize) y=np.zeros(len(t)); for i in range(len(t)): y[i]=int(threeLines(t[i])) fig.scatter(t,y) fig.grid(True) fig.set_xlabel('Y') fig.set_ylabel('X') legend1 = plt.Circle((0, 0), 1, fc="r") legend2 = plt.Circle((0, 0), 1, fc="b") legend3 = plt.Circle((0, 0), 1, fc="g") fig.legend([legend1,legend2,legend3], ["p(y|x) likelihood","Max{p(y|x)} for a specific x","Y distribution"], bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=2, mode="expand", borderaxespad=0.) threeLinesDrawer(0,20) plt.show() '''
You can adjust the space that a set of axes takes within a figure by modifying the subplot parameters. For example, add the following line just before 'plt.show()': ''' plt.subplots_adjust(top=.9, bottom=.1, hspace=.1, left=.1, right=.9, wspace=.1) ''' You should tweak the above values as you see fit in the range of '[0, 1]'. Feel free to get rid of the parameters you're not interested in tweaking (e.g. since you only have one axis in your figure, you won't care about the 'hspace' and 'wspace' parameters, which modify the spacing between subplots). These settings can also be modified through the 'plt.show()' GUI, but you'd have to do it every time you run the script. A set of good settings for your case is the following: ''' plt.subplots_adjust(top=.83, bottom=.08, left=.08, right=.98) ''' For doing this adjustment automatically, you can try using <URL>': ''' plt.tight_layout() ''' This won't necessarily give the intended results in every case, though.
26,827,276
1
26,909,658
I have JSON data and that JSON data has parent child relation . I Want to create tree structure from it. i found many plugins and libraries but i can't found my requirement . I am getting this JSON data using PHP script. Here is image that has tree structure that i want to create . i'm stuck at it.I know JSON is not as displayed in image but i only want to show you what a tree should look like .How to create tree like in image.All i want is javascript code to handle and create this type of structure of tree . Working example is must & much appreciated. You can use JSON format as you like and tree should be collapsible.Also provide required JSON format for it. <IMAGE> and my JSON data as follows : ''' { "2": { "5": "Wrist Watch" }, "5": { "9": "Men's" }, "18": { "3": "Clothing" }, "28": { "1": "Perfumes" }, "29": { "7": "Laptop", "10": "Tablets" }, "30": { "8": "Mobile" }, "31": { "2": "Books" }, "33": { "6": "Electronics" }, "34": { "4": "Home & Kitchen " } } '''
If you want to roll your own, the keyword in "trees" is . It needs to support any depth of data and the code and data should support recursion. This means your JSON data should be a recursive structure, where each node looks the same (and looks something like this): ''' { id: 1, // data id title: "title", // display title children: [ // list of children, each with this same structure // list of child nodes ] } ''' Note: e.g.: ''' { id: 0, title: "root - not displayed", children: [{ id: 1, title: "Option 1", children: [{ id: 11, title: "Option 11", children: [{ id: 111, title: "Option 111" }, { id: 112, title: "Option 112" }] }, { id: 12, title: "Option 12" }] }, { id: 2, title: "Option 2", children: [{ id: 21, title: "Option 21" }, { id: 22, title: "Option 22" }] }, { id: 3, title: "Option 3", children: [{ id: 31, title: "Option 31" }, { id: 32, title: "Option 32" }] }] } ''' The recursive function looks like this: ''' function addItem(parentUL, branch) { for (var key in branch.children) { var item = branch.children[key]; $item = $('<li>', { id: "item" + item.id }); $item.append($('<input>', { type: "checkbox", name: "item" + item.id })); $item.append($('<label>', { for: "item" + item.id, text: item.title })); parentUL.append($item); if (item.children) { var $ul = $('<ul>').appendTo($item); addItem($ul, item); } } } ''' <URL> The code recurses the structure, adding new ULs and LIs (with checkbox etc ) as it goes. The top level call just provides the initial root starting points of both the display and the data. ''' addItem($('#root'), data); ''' The end result looks like this: <IMAGE> If you want to toggle visibility, based on the checked state, use this: ''' $(':checkbox').change(function () { $(this).closest('li').children('ul').slideToggle(); }); ''' If you also want the labels to toggle the checkboxes, use this: ''' $('label').click(function(){ $(this).closest('li').find(':checkbox').trigger('click'); }); ''' Note: -- updated: > amended: possible wrong ids for items 31 & 32? function for better selection and deselection(for parents cascading into child nodes): ''' $(function () { addItem($('#root'), data); $(':checkbox').click(function () { $(this).find(':checkbox').trigger('click'); var matchingId = $(this).attr('id'); if ($(this).attr('checked')) { $('input[id*=' + matchingId +']').each(function() { $(this).removeAttr('checked'); $(this).prop('checked', $(this).attr('checked')); }); } else { $('input[id*=' + matchingId +']').each(function() { $(this).attr('checked', 'checked'); $(this).prop('checked', $(this).attr('checked')); }); } }); $('label').click(function(){ $(this).closest('li').children('ul').slideToggle(); }); ''' -- Update the fiddle with this as shown here(<URL> you to see what values and options are available without having to select the first.
50,774,983
1
50,775,018
The following documentation notification is a distraction, it appears whenever I type 'ejs.render()'. How can I disable it? <IMAGE>
Set '"editor.parameterHints": false' in your user configuration.
14,429,203
1
14,431,571
So I'm working on a node.js game server application at the moment, and I've hit a bit of a wall here. My issue is that I'm using socket.io to accept inbound connections from game clients. These clients might be connected to one of several Zones or areas of the game world. The basic architecture is displayed below. The master process forks a child process for each Zone of the game which runs the Zone Manager process; a process dedicated to maintaining the Zone data (3d models, positions of players/entities, etc). The master process then forks multiple "Communication Threads" for each Zone Manager it creates. These threads create an instance of socket.io and listen on the port for that Zone (multiple threads listening on a single port). These threads will handle the majority of the game logic in their own process as well as communicate with the database backing the game server. The only issue is that in some circumstances they may need to communicate with the Zone Manager to receive information about the Zone, players, etc. <IMAGE> As an example: A player wants to buy/sell/trade with a non-player character (NPC) in the Zone. The Zone Communication thread needs to ask the Zone Manager thread if the player is close enough to the NPC to make the trade before it allows the trade to take place. The issue I'm running into here is that I was planning to make use of the node.js cluster functionality and use the 'send()' and 'on()' methods of the processes to handle passing messages back and forth. That would be fine except for one caveat I've run into with it. Since all child processes spun off with 'cluster.fork()' can only communicate with the "master" process. The node.js root process becomes a bottleneck for all communication. I ran some benchmarks on my system using a script that literally just bounced a message back and forth using the cluster's Inter-process Communication (IPC) and kept track of how many relays per second were being carried out. It seems that eventually node caps out at about 20k per second in terms of how many IPC's it can relay. This number was consistent on both a Phenom II 1.8ghz quad core laptop, and an FX-8350 4.0ghz 8-core desktop. Now that sounds pretty decently high, except that this basically means that regardless of how many Zones or Communication Threads there are, all IPC is still bottlenecking through a single process that acts as a "relay" for the entire application. Which means that although it seems each individual thread can relay > 20k IPCs per second, the entire application as a whole will never relay more than that even if it were on some insane 32 core system since all the communication goes through a single thread. So that's the problem I'm having. Now the dilemma. I've read a lot about the various other options out there and read like 20 different questions here on stack about this topic and I've seen a couple things popping up regularly: <URL> I'm actually running Redis on my server at the moment and using it as the socket.io datastore so that socket.io in multiple threads can share connection data so that a user can connect to any of N number of socket.io threads for their Zone so the server can sort of automatically load balance the incoming connections. My concern with this is that it runs through the network stack. Hardly ideal for communication between multiple processes on the same server. I feel like the latency would be a major issue in the long run. <URL> I've never used this one for anything before, but I've been hearing a bit about it lately. Based on the reading I've done, I've found a lot of examples of people using it with TCP sockets, but there's not a lot of buzz about people using it for IPC. I was hoping perhaps someone here had worked with 0MQ for IPC before (possibly even in node.js?) and could shine some light on this option for me. <URL> Again I've never used this, but from what I've seen it looks like it's another option that is designed to work over TCP which means the network stack gets in the way again. <URL> Someone linked this in another question on here (which I can't seem to find again unfortunately). I've never even heard of it, and it looks like a very small solution that opens up and listens on UDP connections. Although this would probably still be faster than TCP options, we still have the network stack in the way right? I'm definitely like about a mile outside of my "programmer zone" as is here and well into the realm of networking/computer architecture stuff that I don't know much about lol Anyway the bottom line is that I'm completely stuck here and have no idea what the best option would be for IPC in this scenario. I'm assuming at the moment that 0MQ is the best option of the ones I've listed above since it's the only one that seems to offer an "IPC" option for communication protocol which I presume means it's using a UNIX socket or something that's not going through the network stack, but I can't confirm that or anything. I guess I'm just hoping some people here might know enough to point me in the right direction or tell me I'm already headed there. The project I'm working on is a multiplayer game server designed to work "out of the box" with a multiplayer game client both powering their 3D graphics/calculations with Three.js. The client and server will be made open source to everyone once I get them all working to my satisfaction, and I want to make sure that the architecture is as scalable as possible so people don't build a game on this and then go to scale up and end up hitting a wall. Anyway thanks for your time if you actually read all this :)
I think that 0MQ would be a very good choice, but I admit that I don't know the others :D For 0MQ it's transparent what transport you decide to use, the library calls are the same. It's just about choosing particular endpoint (and thus transport) during the call to 'zmq_bind' and 'zmq_connect' at the beginning. There are basically 4 paths you may decide to take: 1. "inproc://<id>" - in-process communication endpoint between threads via memory 2. "ipc://<filepath>" - system-dependent inter-process communication endpoint 3. "tcp://<ip-address>" - clear 4. "pgm://..." or "epgm://..." - an endpoint for Pragmatic Reliable Multicast So to put is simply, the higher in the list you are, the faster it is and the less problems considering latency and reliability you have to face. So you should try to keep as high as possible. Since your components are processes, you should go with the IPC transport, naturally. If you later on need to change something, you can just change the endpoint definition and you are fine. Now what is in fact more important than the transport you choose is the socket type, or rather pattern you decide to use. You situation is a typical request-response kind of communication, so you can either do 1. Manager: REP socket, Threads: REQ socket; or 2. Manager: ROUTER, Threads: REQ or DEALER The Threads would then connect their sockets to the single Manager socket assigned to them and that's all, they can start to send their requests and wait for responses. All they have to decide on is the path they use as the endpoint. But to describe in details what all those socket types and patterns mean is definitely out of the scope of this post, but you can and should read more about it in the <URL> Hope it helped a bit, cheers!
25,682,420
1
25,682,756
<IMAGE> Recently upgraded to VS 2013 which is great but I can't work out how to turn off the code block indicators. I've looked under Tools -> Options -> Editor -> Text Editor but I can't seem to find it. I'm not sure what I should be looking for.
I'm going to guess that you have the 'Productivity Power Tools'extension installed. To turn of the blue lines go to: ''' Tools -> Options -> Productivity Power Tools -> Turn Extensions On/Off ''' and turn off 'Structure Visualizer' which should be the option third from the bottom.
10,714,868
1
10,724,571
I am building an app for iPhone and iPad using PhoneGap and jQM ''' <div class="ui-block-a"> <a id="btnLink" href="#pageID" data-role="button"></a> </div> ''' and it functions fine, but when I run it on the device (didn't try the simulator) and press a long press, I get the default iPhone menu for a link in a normal browser to open or copy the link. how can I disable this default feature in my app? I tried these with no success: ''' $("a").click(function(event) { event.preventDefault(); // long press menu still apear }); $("a").bind('click',function(event) { console.log(['preventingclick',event.type]); event.preventDefault(); // long press menu still apear }); ''' if I bind on 'taphold' I still see the menu on a long press, but after I click cancel I see the console log: ["preventing long press","taphold"] ''' $("a").bind('taphold', function(event) { console.log(['preventing long press',event.type]); event.preventDefault(); // long press menu still apear }); ''' if I use delegate on 'taphold' event like this: ''' $("a").delegate('taphold', function(event) { console.log(['preventing long press',event.type]); event.preventDefault(); }); ''' will fix the problem, but I can't attach any events anymore, so non of my buttons will work after that. ''' $('#btnLink').bind("click", function() { $.mobile.changePage('mypage', 'slide'); // won't fire any more because of the delegate before }); ''' I know that delegate will apply on all elements now and in the future, but I think I am getting close to the answer, but not yet. Thanks in advance <IMAGE>
ok got it to work, I had to combine both code fixes, CSS and JavaScript so in my CSS I did this: ''' body { -webkit-touch-callout: none !important; } a { -webkit-user-select: none !important; } ''' in my JavaScript did this: ''' function onBodyLoad() { $("a").bind('taphold', function(event) { event.preventDefault(); }); } ''' and now all the links are disabled, but if I attach an event to any of them it will work with no problem THanks all
12,202,673
1
12,206,227
I'm totally new to this liquid layout stuff. I've notice, as most of us, that while most of my layout components "liquify", images, unfortunately, don't. So I'm trying to use the 'max-width: 100%' on images as suggested on several places. However, and despite the definition of 'max-width' and 'min-height' of the img , the don't scale. If you see it on a wide resolution, you would notice that the "kid image", for example, don't scale. Any clue about what could the issue be, why does that image not scale? Browsers: / IOS: Resolution: I get an image that doesn't scale until the end of it's container. The img width won't fit the 'article' element that contains it. <IMAGE> I expect the image to enlarge, until it reaches the end it's container. Visually, I'm expecting the image to be as wide as the paragraph immediately below, in a way that, the right side of the image stays vertically aligned with the right side of the paragraph below.
I think you misunderstand what 'max-width' does. 'max-width:100%' means "the maximum width this element can be is 100% of it's container". Anything that's naturally smaller will not be affected. That's what you have now and it's working properly. If you used 'max-width:800px', it would mean "never let this image be more than 800px wide", it wouldn't force an 800px width, that's what 'width' is for. 'width:100%' means "this element should always be 100% width of it's container". Anything that would normally be smaller must now take up the entire width. Anything bigger will shrink to the container's width. For your case, just use 'width:100%' and size your actual images to fit the actual maximum (and pick a reasonable maximum width for the container). Images usually look better when scaled down than scaled up, but when optimizing for mobile devices you might want to do the opposite. The reason you usually see 'max-width:100%' as a default style is so images don't extend beyond their containers and break the layout, since images are usually sized naturally by their actual width.
1,889,701
1
2,194,233
I'm having a hard time even phrasing this question. I'm displaying preview images to users in my UI within a ListBox. When a user hovers over the image, I'd like to expand it so the user can see more detail. I've gotten to the point where I can "pop up" the image, but of course it is still within its normal position in the layout, meaning that rather than the image being displayed on top of the other controls near it, it only appears on top of the controls rendered before it and underneath those rendered after it. It is also being cropped by the bounds of the ListBox. Is there a simple (i.e., no custom control development) way to, temporarily, remove that image from the visual layout and put it above all other elements? Here's a crappy demo app that shows what I'm talking about: <IMAGE> Notice the zoomed image is clipped by the bounds of the ListBox (outside of the list box is red). Also, notice that UI elements rendered after the zoomed image overlay it still--both icons that come later and item names ("Item 5" and others seen in the lower left hand corner).
The solution which worked best for me was using the Popup primitive. It doesn't provide much in the way of control when it comes to animation (it comes with stock animations) but you can animate its contents any which way you like. ''' <Image Name="icon" Source="{Binding MaiImaeg}"> <Image.Triggers> <EventTrigger RoutedEvent="Image.MouseEnter"> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetName="tranny" Storyboard.TargetProperty="ScaleX" To="6" Duration="0:0:1"> <DoubleAnimation.EasingFunction> <ElasticEase Oscillations="1" Springiness="8" /> </DoubleAnimation.EasingFunction> </DoubleAnimation> <DoubleAnimation Storyboard.TargetName="tranny" Storyboard.TargetProperty="ScaleY" To="6" Duration="0:0:1"> <DoubleAnimation.EasingFunction> <ElasticEase Oscillations="1" Springiness="8" /> </DoubleAnimation.EasingFunction> </DoubleAnimation> </Storyboard> </BeginStoryboard> </EventTrigger> <EventTrigger RoutedEvent="Image.MouseLeave"> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetName="tranny" Storyboard.TargetProperty="ScaleX" To="0" Duration="0:0:0" /> <DoubleAnimation Storyboard.TargetName="tranny" Storyboard.TargetProperty="ScaleY" To="0" Duration="0:0:0" /> </Storyboard> </BeginStoryboard> </EventTrigger> </Image.Triggers> </Image> <Popup Name="popup" IsOpen="{Binding IsMouseOver, ElementName=icon, Mode=OneWay}" PlacementTarget="{Binding ElementName=icon}" Placement="Left" Width="640" Height="640" StaysOpen="true" AllowsTransparency="True"> <Image Width="48" Height="48" Source="{Binding MaiImaeg}"> <Image.RenderTransform> <ScaleTransform x:Name="tranny" CenterX="48" CenterY="24" ScaleX="1" ScaleY="1" /> </Image.RenderTransform> </Image> </Popup> ''' In this snippet, the popup is not open until 'IsMouseOver' is true for its Image (named "icon"). When the mouse enters the image, two things happen. The Popup opens (at 640x640) and an image is shown (48px by 48px). This image has a scale transform on it. The "icon" Image also has a storyboard for MouseEnter and MouseLeave. This storyboard uses a double animation, targeted at the popup image's ScaleTransform. This storyboard enlarges the image when the mouse enters and shrinks it when it leaves with a nice easing function. The use case would be: "User is presented a listbox with small images for each item in the list. When the user hovers over the small image (icon), it springs forward and enlarges, giving the user a better view of the image. When the mouse leaves the image, it shrinks back to its original size."
22,842,463
1
22,852,219
how i can set default emulation IE to Edge? In F12 i have selected IE7 and i dont know how return Edge. <IMAGE>
The easiest way to get your page to render in Edge mode is to include a DOCTYPE on the top of your HTML page: ''' <!DOCTYPE html> ''' If you are testing your page locally or on the intranet, you may have to change your Compatibility view settings. These can be found in: ''' "Tools" (Alt+T) -> "Compatibility View Settings" -> And uncheck "Display Intranet Sites in Compatibility View" ''' You can also include the X-UA-Compatible tag, which will force the page to EDGE mode. More information on X-UA-Compatible: <URL> If you have any more questions, you visit <URL>
27,726,180
1
27,761,700
For this example, I'm trying to build a system that will allow output from multiple sources, but these sources are not yet built. The output "module" will be one component, and each source will be its own component to be built and expanded upon later. Here's an example I designed in MySQLWorkbench: <IMAGE> The goal is to make my output module display data from the output table while being easily expanded upon later as more sources are built. I also want to minimize schema updates when adding new sources. Currently, I will have to add a new table per source, then add a foreign key to the output table. Is there a better way to do this? I don't know how I feel about these NULL-able foreign keys because the JOIN query will contains IFNULL's and will get unruly quickly. Thoughts? I will be displaying a grid using data in the output table. The output table will contain general data for all items in the grid and will basically act as an aggregator for the output_source_X tables: ''' output(id, when_added, is_approved, when_approved, sort_order, ...) ''' The output_source_X tables will contain additional data specific to a source. For example, let's say one of the output source tables is for Facebook posts, so this table will contain columns specific to the Facebook API: ''' output_source_facebook(id, from, message, place, updated_time, ...) ''' Another may be Twitter, so the columns are specific for Twitter: ''' output_source_twitter(id, coordinates, favorited, truncated, text, ...) ''' A third output source table could be Instagram, so the output_source_instagram table will contain columns specific to Instagram. There will be a one-to-one foreign key relationship with the output table and ONLY ONE of the output_source_X tables, depending on if the output item is a Facebook, Twitter, Instagram, etc... post, hence the NULL-able foreign keys. ''' output table ------------ foreign key (source_id_facebook) references output_source_facebook(id) foreign key (source_id_twitter) references output_source_twitter(id) foreign key (source_id_instagram) references output_source_instagram(id) ''' I guess my concern is that this is not as modular as I'd like it to be because I'd like to add other sources as well without having to update the schema much. Currently, this requires me to join output_source_X on the output table using whatever foreign key is not null.
This design in almost certainly bad in a few ways. It's not that clear what your design is representing but a straightforward one would be something like: ''' // source [id] has ... source(id,message,...) // output [id] is approved when [approved]=1 and ... output(id,approved,...) // output [output_id] has [source_id] as a source output_source(output_id,source_id) foreign key (source_id) references source(id) foreign key (source_id) references source(id) ''' Maybe you have different subtypes of outputs and/or sources? Based on sources and/or outputs? Maybe each source is restricted to feeding particular outputs? Are "outputs" and "sources" actually of outputs and sources, and this is info not on how outputs are sourced but info on what kinds of output-source pairings are permittted? Please give us statements parameterized by column names for the basic statements you want to make about your application. Ie for the application relationships you are interested in. (Eg like the code comments above.) (You could do it for the diagrammed design but probably that would be overly complicated and not really reflecting what you are trying to model.) Re your EDIT: > There will be a one-to-one foreign key relationship with the output table and ONLY ONE of the output_source_X tables, depending on if the output item is a Facebook, Twitter, Instagram, etc... post, hence the NULL-able foreign keys. You have a case of multiple disjoint subtypes of a supertype. Your situation is a lot like that of <URL>. > Please give us statements parameterized by column names for the basic statements you want to make about your application and you will find straightforward statements (as above). And if you give the statements for your current design you will find them complex. See also this. > I guess my concern is that this is not as modular as I'd like it to be because I'd like to add other sources as well without having to update the schema much. Your structure is not reducing schema changes compared to proper subtype designs. Anyway, DDL is there for that. You can genericize subtypes to avoid DDL only by loss of the DBMS managing integrity. That would be relevant or reasonable based on evaluating DDL vs DML performance tradeoffs. Search re (usually, anti-pattern) EAV. ( after you shown that creating & deleting new tables is infeasible and the corresponding horrible integrity-&-concurrency-challenged mega-joining table-and-metadata-encoded-in-table EAV information-equivalent design is feasible should you consider using EAV.)
17,735,485
1
17,744,558
There are no possibility to see ToolTip on irregular chart when some points placed on the same X line but with different Y values. <IMAGE> actually I expected observe tooltip in that places where mouse positioned and if the graph Point exist in the small radius around. However for the picture above we can observed tooltip only for the higest and pre-higest points, but not for the lowest and pre-lowes points. Thanks
Yes, duplicated points on xAxis are not supported for (sp)line series. You can use scatter series with 'lineWidth: 1' instead.
62,441,300
1
62,443,007
I used matlab code. ''' img = imread('cmap3.png') map = jet(256) ind = rgb2ind(img,map) colormap(map) cm = colormap('gray) image(ind) ''' Through above code, I got the <IMAGE>. I want to save just the gray scale image without any graduations and numbers on x,y axis. How do I remove them and save gray scale image?
If you use <URL>, you won't save the axes' labels. For actual plots, there exists a different solutions, eg. described <URL>'. Than you can even use 'print' to save the image/figure.
55,543,269
1
55,544,047
So I'm using this library: <URL> in my app and have this very annoying issue that I can't seem to find a solution for. <IMAGE> As you can see, just like the screenshots from OP's README, I'm getting the light gray color on my statusbar. I opened an issue but I doubt if I will get any support, considering the fact that OP hasn't updated the library in a while or answered other open issues which brings me here. My app uses AMOLED dark theme overall and this seems to annoy. Also, feel free to let me know if there's an alternative library similar to this. I use this one for the full-width button integration, and custom dialog UI. Thank you.
It seems to be a library error. Until the developer fixes it, you can override the dialog theme to avoid the statusbar color change. Add this to your project's styles.xml file ''' <style name="CFDialog" parent="Theme.AppCompat.Light.Dialog.Alert"> <item name="windowNoTitle">true</item> <item name="android:windowAnimationStyle">@style/CFDialog.Animation</item> <item name="android:windowIsFloating">false</item> <item name="android:backgroundDimAmount">0.0</item> <!-- This line does the magic --> <item name="android:windowTranslucentStatus" tools:targetApi="21">true</item> </style> ''' <IMAGE>
2,688,759
1
2,688,806
Let's say I have a list of branches, how to find a list of tree list that are singly connected together? The below diagram should illustrate my point. The input is a list of branches in a single tree, as labeled, ie. '1', '2', '3' and so on <IMAGE>
The process is as follows: 1. Create a function that accepts a tree node as a parameter 2. If the node has no children, print the value of the current node and return. 3. If the node has two children, end the current list of single node values, then recurse into the left node, then the right node 4. If the node has one child, add it to the list of values contained in the tree, then recurse into that node. 5. Continue.
28,079,960
1
28,092,996
I'm trying to implement a scrollable background into my current GameScene. This is supposed to be done via , which I'm already using for Taps and moving other scene objects. Unlike pretty much every other result returned by my Google searches, I don't want an infinitely scrolling background. It just needs to move with your finger, and stay where it's been moved. Here's what I've got so far for moving my Sprites: ''' -(void)selectTouchedNode:(CGPoint)location { SKSpriteNode *node = (SKSpriteNode *)[self nodeAtPoint:location]; if ([self.selectedNode isEqual:node]){ if (![self.selectedNode isEqual:self.background]){ self.selectedNode = NULL; } } if ([node isKindOfClass:[SKLabelNode class]]){ self.selectedNode = node.parent; } else { self.selectedNode = node; } NSLog(@"Node Selected: %@ | Position: %f, %f",node.name,node.position.x,node.position.y); } - (void)respondToPan:(UIPanGestureRecognizer *)recognizer { if (recognizer.state == UIGestureRecognizerStateBegan) { // Get Touch Location in the View CGPoint touchLocation = [recognizer locationInView:recognizer.view]; // Convert that Touch Location touchLocation = [self convertPointFromView:touchLocation]; // Select Node at said Location. [self selectTouchedNode:touchLocation]; } else if (recognizer.state == UIGestureRecognizerStateChanged) { // Get the translation being performed on the sprite. CGPoint translation = [recognizer translationInView:recognizer.view]; // Copy to another CGPoint translation = CGPointMake(translation.x, -translation.y); // Translate the currently selected object [self translateMotion:recognizer Translation:translation]; // Reset translation to zero. [recognizer setTranslation:CGPointZero inView:recognizer.view]; } else if (recognizer.state == UIGestureRecognizerStateEnded) { // Fetch Current Location in View CGPoint touchLocation = [recognizer locationInView:recognizer.view]; // Convert to location in game. CGPoint correctLocation = [self convertPointFromView:touchLocation]; // If the selected node is the background node if ([self.selectedNode isEqual:self.background]) { NSLog(@"Scrolling the background: Node is: %@",self.selectedNode.name); // Set up a scroll duration float scrollDuration = 0.2; // Get the new position based on what is allowed by the function CGPoint newPos = [self backgroundPanPos:correctLocation]; NSLog(@"New Position: %f, %f",newPos.x,newPos.y); // Remove all Actions from the background [_selectedNode removeAllActions]; // Move the background to the new position with defined duration. SKAction *moveTo = [SKAction moveTo:newPos duration:scrollDuration]; // SetTimingMode for a smoother transition [moveTo setTimingMode:SKActionTimingEaseOut]; // Run the action [_selectedNode runAction:moveTo]; } else { // Otherwise, just put the damn node where the touch occured. self.selectedNode.position = correctLocation; } } } // NEW PLAN: Kill myself - (void)translateMotion:(UIGestureRecognizer *)recognizer Translation:(CGPoint)translation { // Fetch Location being touched CGPoint touchLocation = [recognizer locationInView:recognizer.view]; // Convert to place in View CGPoint location = [self convertPointFromView:touchLocation]; // Set node to that location self.selectedNode.position = location; } - (CGPoint)backgroundPanPos:(CGPoint)newPos { // Create a new point based on the touched location CGPoint correctedPos = newPos; return correctedPos; } ''' I've tried printing the positions before the scrolling, when it ends, and when it gets initiated again. Results are that the background move positions, and once you try to move it again it starts at those new Coordinates, the screen has just itself over the centre of the sprite. <IMAGE>
I'm not sure I 100% understand the situation you are describing, but I believe that it might be related to the anchor point of your background sprite node. in your method: ''' - (void)translateMotion:(UIGestureRecognizer *)recognizer Translation:(CGPoint)translation ''' you have the line: ''' self.selectedNode.position = location; ''' Since your background sprite's anchor point is set to its center by default, any time you move a new touch, it will snap the background sprite's center to the location of your finger. In other words, 'background.sprite.position' sets the coordinates for the background sprite's (which by default is the center of the sprite), and in this case any time you set a new position, it is moving the center to that position. The solution in this case would be to shift the anchor point of the background sprite to be directly under the touch each time, so you are changing the position of the background relative to the point of the background the touch started on. It's a little hard to explain, so here's some sample code to show you: 1) Create a new project in Xcode using the Sprite Kit Game template 2) Replace the contents of GameScene.m with the following: ''' #import "GameScene.h" @interface GameScene () @property (nonatomic, strong) SKSpriteNode *sprite; @end @implementation GameScene -(void)didMoveToView:(SKView *)view { /* Setup your scene here */ self.sprite = [SKSpriteNode spriteNodeWithImageNamed:@"Spaceship"]; self.sprite.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame)); [self addChild:self.sprite]; } -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { /* Called when a touch begins */ UITouch *touch = [touches anyObject]; CGPoint nodelocation = [touch locationInNode:self.sprite]; //[self adjustAnchorPointForSprite:self.sprite toLocation:nodelocation]; CGPoint location = [touch locationInNode:self]; self.sprite.position = location; } -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; CGPoint location = [touch locationInNode:self]; self.sprite.position = location; } -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { } -(void)adjustAnchorPointForSprite:(SKSpriteNode *)sprite toLocation:(CGPoint)location { // Remember the sprite's current position CGPoint originalPosition = sprite.position; // Convert the coordinates of the passed-in location to be relative to the bottom left of the sprite (instead of its current anchor point) CGPoint adjustedNodeLocation = CGPointMake(sprite.anchorPoint.x * sprite.size.width + location.x, sprite.anchorPoint.y * sprite.size.height + location.y); // Move the anchor point of the sprite to match the passed-in location sprite.anchorPoint = CGPointMake(adjustedNodeLocation.x / self.sprite.size.width, adjustedNodeLocation.y / self.sprite.size.height); // Undo any change of position caused by moving the anchor point self.sprite.position = CGPointMake(sprite.position.x - (sprite.position.x - originalPosition.x), sprite.position.y - (sprite.position.y - originalPosition.y)); } -(void)update:(CFTimeInterval)currentTime { /* Called before each frame is rendered */ } @end ''' 3) Run the project in the sim or on a device and click / touch the top tip of the space ship and start dragging. 4) Notice that the spaceship snaps its center point to where your touch is. If you drag and release it to a new location, and the touch the screen again, it snaps its center back to your finger. 5) Now uncomment the line: ''' [self adjustAnchorPointForSprite:self.sprite toLocation:nodelocation]; ''' and run the project again. 6) See how you can now drag the ship where you want it, and when you touch it later, it stays in place and follows your finger from the point you touched it. This is because the anchor point is now being adjusted to the point under the touch each time a new touch begins. Hopefully this gives you a solution you can use in your game as well.
20,930,022
1
20,930,072
in my iOS app I try to populate a core data store the first time the app is executed. I am using following code in my AppDelegate.m file, I will show as example how I am creating one object of the entity: ''' //creating new managedObject NSManagedObject *favoriteThing = [NSEntityDescription insertNewObjectForEntityForName:@"FavoriteThing" inManagedObjectContext:[self managedObjectContext]]; //extracting year,month and day from current date todayDate = [NSDate date]; NSCalendar* calendar = [NSCalendar currentCalendar]; NSDateComponents* components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:todayDate]; // Get necessary date components //converting components NSNumber *yearBuscado = [NSNumber numberWithLong:[components year]]; NSNumber *mesBuscado = [NSNumber numberWithLong:[components month]]; NSNumber *diaBuscado = [NSNumber numberWithLong:[components day]]; //populating managedObject [favoriteThing setValue:@"If done, swipe to right " forKey:@"thingName"];//String [favoriteThing setValue:[NSNumber numberWithInt:10] forKey:@"displayOrder"];//Integer32 [favoriteThing setValue:[NSNumber numberWithInt:yearBuscado] forKey:@"todoYear"];//Integer32 [favoriteThing setValue:[NSNumber numberWithInt:mesBuscado] forKey:@"todoMonth"];//Integer32 [favoriteThing setValue:[NSNumber numberWithInt:diaBuscado] forKey:@"todoDay"];//Integer32 [favoriteThing setValue:@"Urgent" forKey:@"urgent"];//String [favoriteThing setValue:@"Yellow" forKey:@"color"];//String [favoriteThing setValue:@"Not deleted" forKey:@"isSemiDeleted"];//String [favoriteThing setValue:@"Not done" forKey:@"isDone"];//String ''' This is what is stored after launching the app the first time (extracted from SQLite manager): <IMAGE> What I need is to store the expected values for today (2014-01-04): ''' todoYear = 2014 todoMonth = 1 todoDay = 4 ''' These three attributes are from type 'Integer 32' What am I doing wrong? Thank you for your time.
You are mistakenly calling 'numberWithInt' with a NSNumber object, instead call setValue directly with that NSNumber ''' todayDate = [NSDate date]; NSCalendar* calendar = [NSCalendar currentCalendar]; NSDateComponents* components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:todayDate]; // Get necessary date components //converting components NSNumber *yearBuscado = [NSNumber numberWithInteger:[components year]]; NSNumber *mesBuscado = [NSNumber numberWithInteger:[components month]]; NSNumber *diaBuscado = [NSNumber numberWithInteger:[components day]]; [favoriteThing setValue:yearBuscado forKey:@"todoYear"];//Integer32 [favoriteThing setValue:mesBuscado forKey:@"todoMonth"];//Integer32 [favoriteThing setValue:diaBuscado forKey:@"todoDay"];//Integer32 ''' Also, you can generate the Model Classes from CoreData Model. So that you can set values to a 'NSManagedObject' through 'Properties' instead of doing Key-Value Coding. Like ''' FavoriteThing *favoriteThing = [NSEntityDescription insertNewObjectForEntityForName:@"FavoriteThing" inManagedObjectContext:[self managedObjectContext]]; [favoriteThing setBuscado: yearBuscado]; '''
52,358,617
1
52,454,893
In the destination directory (/dist/) I would like to create three directories with IMAGES folder, CSS folder, JS folder, multi output directories similar to the following screenshoot: <IMAGE> My current entry looks something like this: <URL> My 'webpack.config.js' looks something like this (this code works but it doesn't create the structure that I want ): ''' var path = require("path"); const webpack = require('webpack'); const ExtractTextPlugin = require("extract-text-webpack-plugin"); const FileManagerPlugin = require('filemanager-webpack-plugin'); const extractCSS = new ExtractTextPlugin("css/[name]-1.0.0.css"); const extractSASS = new ExtractTextPlugin("es/[name].css"); module.exports = function(env) { var isProd = false; if (env != null && env.production) { isProd = true; } var jsDev = "./js/[name]-bundle.js"; var jsProd = "./js/[name]-" + date_string() + ".js"; var configJs = isProd ? jsProd : jsDev; return { context: path.resolve(__dirname, "src"), entry: { specials: './js/specials.js', checkout: './js/checkout.js', mobile: './js/mobile.js', screen: './js/screen.js', custom: './js/app.js' }, output: { path: path.join(__dirname, "dist"), filename: configJs }, module: { rules: [{ test: /\.css$/, use: extractCSS.extract({ fallback: "style-loader", use: "css-loader" }) }, { test: /\.scss$/, use: extractSASS.extract({ fallback: "style-loader", use: ["css-loader", "sass-loader"] }) }, { test: /\.(jpg|svg|png|gif)$/, exclude: /fonts/, loaders: [{ loader: 'file-loader', options: { name: '[name].[ext]', outputPath: './images/', publicPath: '' } }] }, { test: /\.(eot|svg|ttf|woff|woff2)$/, exclude: /images/, loader: 'file-loader', options: { name: 'fonts/[name].[ext]', publicPath: '' } }] }, plugins: [ extractSASS ] }; ''' Any help will be appreciated, Thank you,
Focus on this part of configuration: ''' var jsDev = "./js/[name]-bundle.js"; var jsProd = "./js/[name]-" + date_string() + ".js"; var configJs = isProd ? jsProd : jsDev; output: { path: path.join(__dirname, "dist"), filename: configJs }, ''' If you change jsDev and jsProd to this: ''' var jsDev = "./[name]/[name]-bundle.js"; var jsProd = "./[name]/[name]-" + date_string() + ".js"; ''' webpack will create folders with your entries names (specials, checkout etc.). If you wish more advanced approach you may check this part of webpack documentation: <URL> , especially the part: ''' module.exports = { //... output: { filename: (chunkData) => { return chunkData.chunk.name === 'main' ? '[name].js': '[name]/[name].js'; }, } }; ''' There are some resources you might want to also check: <URL> <URL> <URL>
50,784,264
1
50,802,604
''' This is a basic program on android to display 2 texviews and 1 button. ''' I am not able to run the below code on my phone. The below has been done in android studio. ''' This is my code- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="QUANTITY" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="0" android:textStyle="bold" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ORDER" /> ''' [<IMAGE>
It looks like you have corrupted build tools 27.0.3. Delete the directory 'C:\Users\dmgop\AppData\Local\Android\Sdk\build-tools\27.0.3\', go to the SDK Manager in Android Studio and re-download build tools 27.0.3. This should fix the issue for you.
35,464,482
1
35,465,785
I want to draw a custom divider in my layout. I know how to draw a straight line divider, but I want something similar to this: <IMAGE> I want the criss-cross lines to be the divider and set the view's background to the same as how we would do it here: ''' <View android:layout_width="match_parent" android:layout_height="1dp" android:background="@android:color/darker_gray"/> '''
You can use a xml bitmap. ''' <bitmap xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/back" android:tileMode="repeat" /> '''
4,169,769
1
4,169,862
I am attempting to use the FileDialog construct in VBA to display a list of available files the user may want to open. I would like to also steer the user towards some common folders in which they typically will find the type of content they are looking for. So far I have come short on locating a method to place a link on the left side of the FileDialog box in which they could click to jump to a specific location. I am hoping there is a means of doing this while calling the FileDialog methods like an example shown below where I have used the 'fd.AddLinkMethod "<path goes here>"'. ''' Private Function GetLocation() As String Dim fd As FileDialog Dim vrtSelectedItem As Variant Set fd = Application.FileDialog(msoFileDialogOpen) fd.ButtonName = "Open" fd.Title = "Select File To Open" fd.InitialView = msoFileDialogViewTiles fd.AddLinkMethod "<path goes here>" With fd If .Show = -1 Then For Each vrtSelectedItem In .SelectedItems GetLocation= FormatPath(vrtSelectedItem) Next vrtSelectedItem End If End With Set fd = Nothing End Function ''' Here is a screenshot of what I am attempting to accomplish? <IMAGE> Any pointers? Thanks,
It should be do-able, but you will need to switch from the access filedialog, and use the Windows Common Dialog from the windows API. ( <URL>. Not the most elegant, but it should work. Goodluck!
5,372,676
1
5,374,037
This may have a simple solution which I haven't found yet. but here's the situation. I have a data in Excel sheet: <IMAGE> This is a log file generated from simulations. The simulation is run tens of times (variable) and each run generates one block starting at "-------------------" and ending before the next "-----------------" divider. The number of rows between these dividers is variable but certain things are fixed. the number and order of columns and the first row & cell being the divider, the next row in the same column having date stamp, the next row having column headings. the divider and date stamp are contained in only 1 cell. What I need to do is mind the MAX of CNT & SIM_TIME for each simulation run. I will then take the average of these. I only need to do this for the "Floor 1" table from the screenshot. What's the best way to proceed? which functions should I use? (I have Office 2010 if that has new functions not present in 2007)
General approach, by example: Data sheet: Sheet1 Results on seperate sheet: Sheet2 Number of rows in data: Cell F2 =COUNTA(Sheet1!B:B) Intermediate result, Row of data set Cell A3 =MATCH(Sheet1!$B$1,OFFSET(Sheet1!$B$1,A2,0,$F$2),0)+A2 Intermediate result, row of next data Cell B3 =IF(IFERROR(N(A4),0)=0,IF(ISNA(A3),"",$F$2),A4) Max of CNT data set, Cell C3 =IF(B3<>"",MAX(OFFSET(Sheet1!$B$1,$A3+2,0,$B3-$A3-3)),"") Max of SIM_TIME, Cell D3 =IF(C3<>"",MAX(OFFSET(Sheet1!$B$1,$A3+2,3,$B3-$A3-3)),"") Date from data set =IF(D3<>"",OFFSET(Sheet1!$B$1,$A3,),"") To expand to give results for all available data, copy range C3:E3 down for as many rows as are in data. any extra rows will show N/A in column A and blanks in others Screen shot of results: <IMAGE> Screen Shot of formulas: <IMAGE>
26,052,398
1
29,162,216
I made a SSRS sql report and uploaded into CRM 2011 report solution. Things were all good until I discovered that when using the zoom tool in the CRM report toolbar in IE, the report content disappears. Neither Chrome or Firefox have this zoom tool in the tool bar. Anyway my main browser is IE. When zoom is 100% it looks great. When it is 200% I cannot see the top half of the report. When I change to zoom 500% report content totally disappears. How do I keep it from disappearing? <IMAGE>
We have installed the CRM 2011 RU 18 and this issue is working fine. <URL>
42,581,305
1
42,581,422
I want to be able to check if user in 'B2' has access to applications in 'A3:A6'. I have a list of all users and what they have access too, how will I be able to match and compare both lists and place a Yes or No in the table? Please see the example from the screenshot below: <IMAGE> I've had a look at 'VLookups' etc but any help wouldn't go a miss!
Use this array formula: ''' =IF(ISNUMBER(MATCH(B$1&$A2,$H$2:$H$15&$G$2:$G$15,0)),"Y","N") ''' Being an array formula it needs to be confirmed with Ctrl-Shift-Enter instead of enter when exiting edit mode. If done correctly then Excel will put '{}' around the formula. <URL>
18,083,689
1
18,087,405
I am trying add method level security to my Spring MCV/Security. The application works if don't add '<security:global-method-security pre-post-annotations="enabled"/>'. I want method level security on controller methods which have request mappings Tomcat error FAIL - Application at context path /commerce could not be started <IMAGE> Here are all my files. ''' <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:security="http://www.springframework.org/schema/security" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- Declare a view resolver --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" /> </beans> ''' ''' <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security="http://www.springframework.org/schema/security" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd"> <!-- This is where we configure Spring-Security --> <security:http auto-config="false" use-expressions="true" access-denied-page="/auth/denied" entry-point-ref="authenticationEntryPoint" > <security:intercept-url pattern="/auth/login" access="permitAll"/> <security:intercept-url pattern="/main/admin" access="hasRole('ROLE_ADMIN')"/> <security:intercept-url pattern="/main/common" access="hasRole('ROLE_USER')"/> <security:logout invalidate-session="true" logout-success-url="/auth/login" logout-url="/auth/logout"/> <security:custom-filter ref="blacklistFilter" before="FILTER_SECURITY_INTERCEPTOR"/> <security:custom-filter ref="authenticationFilter" position="FORM_LOGIN_FILTER"/> </security:http> <!-- Custom filter to deny unwanted users even though registered --> <bean id="blacklistFilter" class="org.krams.commerce.filter.BlacklistFilter" /> <!-- Custom filter for username and password. The real customization is done in the customAthenticationManager --> <bean id="authenticationFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter" p:authenticationManager-ref="customAuthenticationManager" p:authenticationFailureHandler-ref="customAuthenticationFailureHandler" p:authenticationSuccessHandler-ref="customAuthenticationSuccessHandler" /> <!-- Custom authentication manager. In order to authenticate, username and password must not be the same --> <bean id="customAuthenticationManager" class="org.krams.commerce.manager.CustomAuthenticationManager" /> <!-- We just actually need to set the default failure url here --> <bean id="customAuthenticationFailureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler" p:defaultFailureUrl="/auth/login?error=true" /> <!-- We just actually need to set the default target url here --> <bean id="customAuthenticationSuccessHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler" p:defaultTargetUrl="/main/common" /> <!-- The AuthenticationEntryPoint is responsible for redirecting the user to a particular page, like a login page, whenever the server sends back a response requiring authentication --> <!-- See Spring-Security Reference 5.4.1 for more info --> <bean id="authenticationEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint" p:loginFormUrl="/auth/login"/> <!-- The tag below has no use but Spring Security needs it to autowire the parent property of org.springframework.security.authentication.ProviderManager. Otherwise we get an error A probable bug. This is still under investigation--> <security:authentication-manager/> </beans> ''' ''' <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:security="http://www.springframework.org/schema/security" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <security:global-method-security pre-post-annotations="enabled"/> <!-- Activates various annotations to be detected in bean classes --> <context:annotation-config /> <!-- Scans the classpath for annotated components that will be auto-registered as Spring beans. For example @Controller and @Service. Make sure to set the correct base-package--> <context:component-scan base-package="org.krams.commerce" /> <!-- Configures the annotation-driven Spring MVC Controller programming model. Note that, with Spring 3.0, this tag works in Servlet MVC only! --> <mvc:annotation-driven /> </beans> ''' ''' <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.krams.tutorial</groupId> <artifactId>commerce</artifactId> <packaging>war</packaging> <version>1.0.0-SNAPSHOT</version> <name>commerce</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.1</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>3.0.5.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>3.0.5.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.14</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>3.0.5.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.1.2</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.0.5.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>3.0.5.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>3.0.5.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>3.0.5.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>3.0.5.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>1.3</version> </dependency> </dependencies> <build> <finalName>commerce</finalName> </build> </project> ''' ''' <?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/spring-security.xml /WEB-INF/applicationContext.xml </param-value> </context-param> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app> ''' ''' Aug 6, 2013 5:00:41 PM org.apache.catalina.loader.WebappClassLoader validateJarFile INFO: validateJarFile(/opt/apache-tomcat-7.0.42/webapps/commerce/WEB-INF/lib/servlet-api-2.5.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class [ERROR] [http-bio-80-exec-382 05:00:41] (ContextLoader.java:initWebApplicationContext:220) Context initialization failed org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 16 in XML document from ServletContext resource [/WEB-INF/applicationContext.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 16; columnNumber: 65; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'security:global-method-security'. at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:124) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:93) at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130) at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:467) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:397) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4939) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.manager.ManagerServlet.start(ManagerServlet.java:1256) at org.apache.catalina.manager.HTMLManagerServlet.start(HTMLManagerServlet.java:714) at org.apache.catalina.manager.HTMLManagerServlet.doPost(HTMLManagerServlet.java:219) at javax.servlet.http.HttpServlet.service(HttpServlet.java:647) at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.filters.CsrfPreventionFilter.doFilter(CsrfPreventionFilter.java:212) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:611) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1146) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:679) Caused by: org.xml.sax.SAXParseException; lineNumber: 16; columnNumber: 65; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'security:global-method-security'. at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198) at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError( at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError( at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator$XSIErro at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.reportS at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleS at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.emptyEl at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scan at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImp at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(X at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImp at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(X at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(X at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser. at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser. at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Doc at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocum at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadB ... 43 more Aug 6, 2013 5:00:41 PM org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart Aug 6, 2013 5:00:41 PM org.apache.catalina.core.StandardContext startInternal SEVERE: Context [/commerce] startup failed due to previous errors '''
I put '<security:global-method-security pre-post-annotations="enabled"/>' this into spring-security and there was a dependency missing. Once I added that it worked just fine. ''' <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2</version> </dependency> '''
67,546,438
1
67,546,558
I wrote a .DLL library with a very simple extension method for 'string'. My method - '.Remove(char deletedChar)', removes all occurrences of a 'char' in a 'string'. This overloads the default '.Remove(int startIndex)' method. However, when I want to use it, '.Remove(int startIndex)' is invoked, instead of my method, despite me giving 'char' as the argument. What I mean is, given this code: ''' string Test = "12-34-56-78-90-123-<PHONE>-89012-34567-890123-456789-000000"; MessageBox.Show(Test.Remove('-')); ''' My expected result is: ''' 1234567890123456789012345678901234567890123456789000000 ''' However, the actual result is: ''' 12-34-56-78-90-123-<PHONE>-89012-34 ''' Check it out on the screenshot: <IMAGE> This means, that my 'char '-'' is interpreted as its ASCII value (45), and this is the start index for removal of the string. Why does this happen? Even casting 'char' to a 'char' (i.e. '(char)'-'') does not fix it. I know I can simply rename the extension method, but I still cannot understand why does this happen. Could someone explain this phenomenon or point to a doc that explains it? Pasting my extension method in case someone will want to use it: ''' /// <summary> /// Removes all occurences of specified char. /// </summary> /// <param name="str"></param> /// <param name="deletedChar">The char you want to remove.</param> /// <returns>string without the specified char.</returns> public static string Remove(this string str, char deletedChar) { for (int i = 0; i < str.Length; i++) { if (str[i] == deletedChar) { str = str.Remove(i, 1); i--; } } return str; } '''
C# instances methods are called before extensions if found. From the <URL>: > When the compiler can't find an instance method with a matching signature, it will bind to a matching extension method if one exists. Writing this helper class, we can see that the good method is called: ''' public static class StringHelper { public static string MyRemove(this string str, int index) { return "remove at index"; } public static string MyRemove(this string str, char code) { return "remove all chars"; } } ''' ''' Console.WriteLine("".MyRemove(1)); Console.WriteLine("".MyRemove('a')); ''' ''' remove at index remove all chars ''' Thus the solution is to use a dedicated method's name: ''' public static class StringHelper { public static string RemoveAll(this string str, char deletedChar) { for ( int i = 0; i < str.Length; i++ ) { if ( str[i] == deletedChar ) { str = str.Remove(i, 1); i--; } } return str; } } ''' Therefore the design and the usage is more clear and clean, as well as more more speaking while the type of the parameter tells what to remove. But such a method is not optimized and can for example be replaced by: ''' public static string RemoveAll(this string str, char code) { return str.Replace(code.ToString(), ""); } ''' Or by this one which is better: ''' using System.Text; public static string RemoveAll(this string str, char code) { var builder = new StringBuilder(); foreach ( char c in str ) if ( c != code ) builder.Append(c); return builder.ToString(); } ''' Or using Linq, but probably less optimized than the previous: ''' using System.Linq; public static string RemoveAll(this string str, char code) { return new string(str.Where(c => c != code).ToArray()); } '''
9,299,386
1
9,299,573
Recently, after some discussions, I decided to use List for social buttons such as Google+, Facebook-like and twitter-follow. Example (under Follow us Section): <IMAGE> I would like to know if using Form inside List item ('<li>') has any effect in SEO. If it has, what's the effect? Simply - is it right to use form inside '<li>' as shown in the example above? Thank you very much!
There's no reason to think that nesting a form inside a list item would affect search engine behavior. What search engines do with forms in the first place is a different matter, and depends on the form and on the search engine.
51,200,054
1
51,200,713
PowerShell gives me this output back when running a command: <IMAGE> I'm having trouble trying to split it, because it's not tab-separated, is space-separated, therefore when i use '.split("")' the column 'Module-Type' is being separated incorrectly because its content also has spaces. I'm new at this, any help would be appreciated. Here's my code: ''' $RS = .\Plink server@puttysession -pw "password" "command" foreach ($RSln in $RS){ $arr = $RSln.split('',[System.StringSplitOptions]::RemoveEmptyEntries) Write-Host $RSln "|" $arr.Length } ''' This gives me the line and the length of the created array, the first two lines are arrays with 5 as length, the third and fourth have 9 items because of the spaces in 'ModuleType'
The recommended way of handling this kind of input in PowerShell is to parse it into custom objects. You can do that either with a regular expression: ''' $RS | Where-Object { $_ -match '(\d+)\s+(\d+)\s+(.*?)\s+([a-z]+(?:-[a-z0-9]+){2,})\s+(.*)' } | ForEach-Object { New-Object -Type PSObject -Property @{ 'Mod' = [int]$matches[1] 'Ports' = [int]$matches[2] 'ModuleType' = $matches[3] 'Model' = $matches[4] 'Status' = $matches[5] } } ''' or (if the columns are of fixed width) by extracting substrings at defined offsets: ''' $RS | Select-Object -Skip 2 | ForEach-Object { New-Object -Type PSObject -Property @{ 'Mod' = [int]$_.Substring(0, 3).Trim() 'Ports' = [int]$_.Substring(5, 5).Trim() 'ModuleType' = $_.Substring(12, 35).Trim() 'Model' = $_.Substring(48, 18).Trim() 'Status' = $_.Substring(67).Trim() } } ''' The 'Select-Object -Skip 2' is needed to skip over the 2 header lines. If all columns were separated by more than one space splitting via '-split '\s\s+'' (split at 2 or more consecutive whitespace characters) would work too. However, with your data that is not the case, since at least the first 2 data rows have only a single space between the 3rd and 4th column.
70,362,896
1
70,364,655
is it possible to achieve the aimed scenario? ''' <!DOCTYPE html> <html> <head> <title>My Product Brand Name</title> </head> <body> <!-- api.localaccountsignup section --> <div id="api1"></div> <!-- api.signuporsignin --> <div id="api2"></div> </body> </html> ''' Ideally, I'd have a frontend that hosts local account signup and signup or signing, as the image below <IMAGE>
Create 2 policies. 1. A Sign Up policy. It will use B2C to render the "Full Name", "Email" and "Password" fields. Use custom HTML to add 3 buttons "Google", "Facebook", "LinkedIn". Each button will link to your application: myapp.com/<social_provider_name>. When a user hits one of these links, the app should send the user to the 2nd policy with a respecticve domain_hint parameter. 2. This policy will have "Google", "Facebook", "LinkedIn" IdPs configured. Each will be configured for direct sign in. The app will pass a parameter domain_hint based off of the users action from Policy 1, and will then cause the user to hit the Social IdP they selected. Adding parameters using MSAL: <URL>
21,309,817
1
33,612,416
Intellisense does not work in razor files: <IMAGE> In my web.conifg file (in the Views folder) is apparently correct: ''' <?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" /> <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" /> </sectionGroup> </configSections> <system.web.webPages.razor> <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <pages pageBaseType="System.Web.Mvc.WebViewPage"> <namespaces> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> <add namespace="System.Web.Optimization" /> <add namespace="MvcSiteMapProvider.Web.Html" /> <add namespace="MvcSiteMapProvider.Web.Html.Models" /> <add namespace="DevTrends.MvcDonutCaching" /> </namespaces> </pages> </system.web.webPages.razor> <appSettings> <add key="webpages:Enabled" value="false" /> </appSettings> <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <handlers> <remove name="BlockViewHandler" /> <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" /> </handlers> </system.webServer> </configuration> '''
This is what worked for me after IntelliSense suddenly began to bug out and stopped colouring C# code correctly in between the HTML tags in my views: --- Just delete the contents of the folder at '%LOCALAPPDATA%\Microsoft\VisualStudio.0_<hash>\ComponentModelCache' --- <URL> As an additional step, you can optionally run the command 'DevEnv.exe /setup' in Developer Command Prompt for VS (as an Administrator) if the above step doesn't resolve the issue.
23,719,570
1
23,719,674
Hi I have managed to get Allegro working within XCODE 5.1.1. I am working through the tutorials and examples and have come across this error when defining the class: <IMAGE> Can anyone help? The writing is not purple as should be either, have I missed a vital include file or something?
Found the problem on a post here <URL> I needed to create the file as C++ and not C as I had done. This fixed it.
41,023,807
1
41,024,445
I would like to add and nudge a text label in ggplot, but nudge_x when x is POSIXct class does not change anything, no matter the value. Sample code here: ''' library(ggplot2) start.time <- c("7:00", "8:00", "9:30") end.time <- c("10:00", "11:00", "13:30") market <- c("Name1", "Name2", "Name3") df <- data.frame(market, start.time, end.time) df$start.time <- as.POSIXct(df$start.time, format="%H:%M") df$end.time <- as.POSIXct(df$end.time, format="%H:%M") df$length <- df$end.time - df$start.time ggplot(df) + geom_segment(aes(x = start.time, xend = end.time, y = market, yend = market), color = "darkgreen", size = 2) + geom_text(aes(x = min(start.time), y = market, label = length), hjust = 0, size = 3, color = "darkgreen", nudge_x = -1) ''' Creates this image: <IMAGE> I would like the labels for the length of the lines to be further to the left. I do not think nudge_x = -1 is registering because it is not the correct class. Thanks!
On datetime scale nudge_x=-1 shifts to left by 1 sec, which is not visible, may be you want to nudge by 1 hr (3600 secs): ''' ggplot(df) + geom_segment(aes(x = start.time, xend = end.time, y = market, yend = market), color = "darkgreen", size = 2) + geom_text(aes(x = min(start.time), y = market, label = length), hjust = 0, size = 3, color = "darkgreen", nudge_x = -3600) ''' <URL> To nudge by 15 mins use to 'nudge_x = -15*60'
11,258,476
1
11,258,889
I'm using to show a temperature graph. on X axis I put dates, to fit them I call setXLabelsAngle(45); this is the result: <IMAGE> As you can see, the labels are and go over the x-Axis. How could I fix this? I'm already using setMargins(), but labels don't move, only legend does.
This will help: ''' renderer.setXLabelsAlign(Align.LEFT); '''
4,988,658
1
4,988,725
I have a model as follows: ''' namespace Q01.Models { public enum Sex { Male, Female } public class Person { public string Name { get; set; } public Sex? Sex { get; set; } } } ''' A utilities class to obtain a 'SelectList' object to populate a 'DropDownListFor' is defined as follows: ''' using System; using System.Linq; using System.Web.Mvc; namespace Q01.Utilities { public static class Utilities { public static SelectList EnumToSelectList<TEnum>(this TEnum? obj) where TEnum: struct { var values = from TEnum x in Enum.GetValues(typeof(TEnum)) select new { Value = x, Text = x }; return new SelectList(values, "Value", "Text"); } } } ''' I create a templated helper named 'Sex.cshtml' for the type of 'Sex' as follows: ''' @using Q01.Utilities @using Q01.Models @model Sex? @Html.DropDownListFor(x => x, Model.EnumToSelectList(), "--Select--") ''' In 'HomeController', I create an instance of 'Person' and pass it to the view as follows: ''' using System.Web.Mvc; using Q01.Models; namespace Q01.Controllers { public class HomeController : Controller { public ActionResult Create() { Person p = new Person(); p.Sex = Sex.Female; return View(p); } } } ''' And the corresponding view is declared as follows: ''' @using Q01.Utilities @model Q01.Models.Person @using (Html.BeginForm()) { <div>Using Sex.cshtml: @Html.EditorFor(x => x.Sex)</div> <div>Not using Sex.cshtml: @Html.DropDownListFor(x => x.Sex, Model.Sex.EnumToSelectList(), "--Select--")</div> } ''' The screenshot of the output is shown as follows: <IMAGE> The question is: why the 'Sex.cshtml' does not reflect the model? It should select 'Female' rather than "--Select--".
Add value to 'EnumToSelectList': ''' public static class Utilities { public static SelectList EnumToSelectList<TEnum>(this TEnum? obj, object value) where TEnum: struct { var values = from TEnum x in Enum.GetValues(typeof(TEnum)) select new { Value = x, Text = x }; return new SelectList(values, "Value", "Text", value); } } ''' Then 'Model.EnumToSelectList(x.Sex)'. You just have to provide selected value in 'SelectList' constructor.
48,428,766
1
48,435,580
I have a text file filled with several lines of data, and I would like to split it into 5 different elements like so.. <IMAGE> I am successfully reading in the data and putting it into an array. Now I would like to split each part of the text up into different lists so I can compare the data against one another. I have currently managed to read in the first 4 elements of each line into their relevant lists but the 5th one is throwing me the error "System.IndexOutOfRangeException" which I can only assume is because the first line it reads in has no value for the 5th element? So my question is, is there a way to populate null values when writing them to a number of lists? I've tried manually assigning the size of the array and lists but I still get the same error. Here is my code: ''' class Program { static void Main(string[] args) { // Reading in file containing data from BT Code Evaluation sheet (for testing purposes). // Each line gets stored into a string array, each element is one line of the data.txt file. //String[] lines = System.IO.File.ReadAllLines(@"C:\Users\Ad\Desktop\data.txt"); String[] lines = new String[5] {"monitorTime", "localTime", "actor", "action", "actor2"}; lines = System.IO.File.ReadAllLines(@"C:\Users\Ad\Desktop\data.txt"); char delimiter = ' '; List<String> monitorTime = new List<String>(); List<String> localTime = new List<String>(); List<String> actor = new List<String>(); List<String> action = new List<String>(); List<String> actor2 = new List<String>(); // Foreach loop displays the lines of text in the data file. foreach (String line in lines) { // Writes the data to the console. Console.WriteLine(line); String[] data = new String[5] { "monitorTime", "localTime", "actor", "action", "actor2" }; data = line.Split(delimiter); monitorTime.Add(data[0]); localTime.Add(data[1]); actor.Add(data[2]); action.Add(data[3]); actor2.Add(data[4]); } foreach (String time in monitorTime) { Console.WriteLine(time); } foreach (String time in localTime) { Console.WriteLine(time); } foreach (String name in actor) { Console.WriteLine(name); } foreach (String actions in action) { Console.WriteLine(actions); } foreach (String name in actor2) { if (name != null) { Console.WriteLine("UNKNOWN"); } else { Console.WriteLine(actor2); } } // Creates an empty line between the data and the following text. Console.WriteLine(""); // Displays message in console. Console.WriteLine("Press any key to analyse data and create report..."); Console.ReadKey(); } } '''
You need to check the bounds of you array before you try to add. If their aren't enough items you can add null instead. For example: ''' actor2.Add(data.length > 4 ? data[4] : null) ''' (Note: You could do the same type of check on the other items as well, unless you are positive that the last item is the only one that might be null) This is using the <URL>, but you could also use a simple 'if/else', but it'll be more verbose. It's equivalent to: ''' if (data.length > 4) { actor2.Add(data[4]); } else { actor2.Add(null); } ''' This along with 'Console.WriteLine(name);' instead of 'Console.WriteLine(actor2);' should fix you immediate problem. However, a much better design here would be to have a single list of objects with 'MonitorTime', 'LocalTime', 'Actor', 'Action' and 'Actor2' properties. That way you don't ever have to worry that the 5 parallel arrays might get out of sync. For example, create a class like this: ''' public class DataItem { public string MonitorTime { get; set; } public string LocalTime { get; set; } public string Actor { get; set; } public string Action { get; set; } public string Actor2 { get; set; } } ''' Then instead of your 5 'List<String>', you have one 'List<DataItem>': ''' List<DataItem> dataList = new List<DataItem>(); ''' Then in your loop to populate it you'd do something like: ''' data = line.Split(delimiter); dataList.Add(new DataItem() { MonitorTime = data[0], LocalTime = data[1], Actor = data[2], Action = data[3], Actor2 = data.length > 4 ? data[4] : null }); ''' Then you can access them later with something like: ''' foreach (var item in dataList) { Console.WriteLine(item.MonitorTime); //... } '''
27,332,748
1
27,432,352
I've created a new "Report Server Project" in VS2013 .Net 4.5. I've added a data source and the test connection succeeds. I've added a DataSet using the "Use a dataset embedded in my report" option choosing the data source previously created. The query type is Stored Procedure with a single text parameter. In the report data box I can right click my DataSet, choose Query, and execute the sproc. I see a grid populated correctly with my data. However, when I try to create and preview a report it fails. I do the following: Add a new report. Drop a table on it from the toolbox. Start dragging fields from my DataSet onto the table. When I hit preview I see the following <IMAGE>
This is a "HACK" but it will do what you are asking. ''' <%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication24._Default" %> <%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-2.1.1.js"></script> <script type="text/javascript"> $(document).ready(function () { Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(pageLoadingHandler); function pageLoadingHandler() { fixParameters(); } function fixParameters() { $("table[id^='ParametersGridReportViewer1']").find('input[type=text]').each(function () { if (isDate($(this).attr("value"))) { $(this).val($(this).val().substring(0, 10)); } }); } function isDate(date) { return ((new Date(date) !== "Invalid Date" && !isNaN(new Date(date)))); } }); </script> </head> <body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> <rsweb:ReportViewer ID="ReportViewer1" runat="server" Font-Names="Verdana" Font-Size="8pt" ProcessingMode="Remote" WaitMessageFont-Names="Verdana" WaitMessageFont-Size="14pt" Width="1184px" ShowParameterPrompts="True"> <ServerReport ReportPath="/Report Project1/Report1" /> </rsweb:ReportViewer> </div> </form> </body> </html> ''' Replace the "ReportViewer1" with the name of your report viewer. This basically will check all input fields inside the report parameter table and if any of them look like dates then it will remove the time while loading. Added entire page code.
5,912,013
1
5,927,178
I am writing a backend surveys database. The database is the backend for multiple applications that are used for gathering survey type data. I have a schema that includes a table that designates the application and what questions belong to that application. now I need to setup users and userroles... each user may have access to 1 or more applications each application has 1 or more users each user may have 1 role in the application they have access to each role may exist in 1 or more applications each user may have different roles in each application. app1 has 15 users 1 user is admin app1 has 2 roles defined for user access app2 has 30 users admin user from app1 has access but is regular user 2 admin users in app2 exist in app1 as normal users app2 has 4 roles defined for user access. so I have Application ->ApplicationUsers<-Users maybe I only need one joining table then like this? <IMAGE> Would that be correct? Would it work in EF 4.0? What would be the correct way to make this work?
Let's assume that this > each user may have 1 role in the application they have access to each role may exist in 1 or more applications each user may have different roles in each application. should be punctuated like this. > Each user may have 1 role in the application they have access to, each role may exist in 1 or more applications, each user may have different roles in each application. If that first clause means that each user have one and no more than one role in each application they have access to, then your schema won't work. The compound primary key {ApplicationId, UserID, RoleID} in ApplicationUserRoles allows multiple roles per user. To limit the constraint "one row (and one role) per user per application", the primary key for ApplicationUserRoles should be just {ApplicationID, UserID}. Also, if UserID is unique in the table Users, it should probably be the primary key, and you should probably drop the column "ID" from that table.
11,494,716
1
11,494,923
I am currently storing in MySQL database image names for easier way to retrieve the actual images. I am having problems with the php code I created that stores the names. Duplicate and blank insertions are being made into the DB without my permission. Is there a way to avoid this issue of duplicate or blank values being inserted when the page refreshed? <IMAGE> ''' <? $images = explode(',', $_GET['i']); $path = Configuration::getUploadUrlPath('medium', 'target'); if (is_array($images)) { try { $objDb = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass); $objDb->exec('SET CHARACTER SET utf8'); } catch (PDOException $e) { echo 'There was a problem'; } $sql = "INSERT INTO 'urlImage' ('image_name') VALUES "; foreach ($images as $image) { $value[] = "('" . $image . "')"; // collect imagenames } $sql .= implode(',', $value) . ";"; //build query $objDb->query($sql); } ?> '''
I reformatted things into what I think should be slightly more readable and more easily separate what's going on in the code. I also updated your queries to show how you can properly "sanitize" your input. I still think the process by which you're going about sending the data to the server is wrong, but hopefully this code helps you out a little bit. I'd also do this more object orientedly.. but I feel that leaves the scope of your question just a little bit =P. It's kind of like everyone else is saying though, the logic for your code was only off . As for the duplication thing, look into checking if the file already exists before adding it to the database. ''' <?php $_GET['i'] = 'file1.png, file2.png, file3.png'; // This is just for testing ;]. $images = retrieve_images(); insert_images_into_database($images); function retrieve_images() { //As someone else pointed out, you do not want to use GET for this and instead want to use POST. But my goal here is to clean up your code //and make it work :]. $images = explode(',', $_GET['i']); return $images; } function insert_images_into_database($images) { if(!$images)//There were no images to return return false; $pdo = get_database_connection(); foreach($images as $image) { $sql = "INSERT INTO 'urlImage' ('image_name') VALUES ( ? )"; $prepared = $pdo->prepare($sql); $prepared->execute(array($image)); } } function get_database_connection() { $host = 'localhost'; $db = 'test'; $user = 'root'; $pass = ''; try { $pdo = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass); $pdo->exec('SET CHARACTER SET utf8'); } catch(PDOException $e) { die('There was a problem'); } return $pdo; } '''
24,661,981
1
24,662,071
I have search view in my fragment. when I click on it , keyboard is open and I can type text. I want when I click on search button in keyboard , my query send to my server and get result but I don't know how get search event. any solution?<IMAGE>
You have to extend <URL>. Example: ''' @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); searchView = (SearchView) menu.findItem(R.id.mActionSearch).getActionView(); searchView.setOnQueryTextListener(this); return true; } @Override public boolean onQueryTextSubmit(String query) { //Do something here return false; } @Override public boolean onQueryTextChange(String newText) { return false; } '''
21,621,581
1
22,684,361
I have an HTML file which includes a JS file in the head tag.. ''' <script type='text/javascript' src='lib/head.core.min.js'></script> <script type='text/javascript' src='custom/my.js'></script> ''' In the file I try to load another JS file to use in : ''' head.load("custom/foo.js"); ''' But anytime I try to execute a function from I get the following error: <IMAGE> Am I doing something in an incorrect way?
You need to include 'head.load.min.js', not 'head.core.min.js' to use the 'head.load' function.
15,743,243
1
15,743,389
Is there an api which would help me gather all the review information from playstore, given the app name? The requirement is to replicate a screen more or less similar to the Playstore "Detailed Review" screen(attached here for quick reference). Any help is appreciated. <IMAGE>
I am confused. Do you want to create a screen that has the layout of the screen you attached or do you want to be able to read the actual review and do something with them? If it is the latter, then there is no Play Store API unfortunately. It probably has to do with privacy issues, I think. If you want a screen that has the same layout, then I don't think you need to gather the review information. I searched around and I found this: <URL> There is more information about the Play Store API here: <URL>
69,304,298
1
69,305,139
I apologize if I come across naive, I am new to Selenium and still learning. We are attempting to run these selenium tests on a designated machine via IIS. When I run the code locally, everything works perfectly. When I publish it to our machine, two instances of chromedriver will show up in the taskmanager when it is only being run once. Sometimes it will close one of the instances, while other times it doesn't close either. Sometimes it will even close both instances and work just fine. I can not figure out why it's being so inconsistent. Here is a screen shot of the task manager after starting the code. <IMAGE> Any suggestions on this is welcome, below is the code I am running. ''' private IWebDriver _driver; [Route("/Test_SignIn")] public IActionResult Test_SignIn(string environment = "development") { string response = "Failed"; try { string outPutDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); _driver = new ChromeDriver(outPutDirectory); if (environment == "production") { _driver.Navigate().GoToUrl(productionUrl); } else { _driver.Navigate().GoToUrl(developmentUrl); } By userNameFieldLocator = By.Id("AccountUserName"); WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(30)); wait.Until(ExpectedConditions.ElementIsVisible(userNameFieldLocator)); _waitForLoaderToFinish(); IWebElement userNameField = _driver.FindElement(userNameFieldLocator); IWebElement passwordField = _driver.FindElement(By.Id("AccountPassword")); IWebElement signInButton = _driver.FindElement(By.XPath("//button[contains(text(), 'Sign In')]")); userNameField.SendKeys(_username); passwordField.SendKeys(_password); signInButton.Click(); By dashboardLocator = By.Id("portalBanner_EmployeeName"); wait.Until(ExpectedConditions.ElementIsVisible(dashboardLocator)); IWebElement dashboard = _driver.FindElement(dashboardLocator); response = "Success"; } catch (Exception ex) { response = ex.Message; } _driver.Close(); _driver.Quit(); return Json(response); } private string _waitForLoaderToFinish() { try { new WebDriverWait(_driver, TimeSpan.FromSeconds(30)).Until(ExpectedConditions.InvisibilityOfElementLocated(By.Id("loader-wrapper"))); return null; } catch (TimeoutException e) { return $"{e.Message}"; } } '''
ChromeDriver (and all other web drivers) are "disposable" objects in .NET. They implement the <URL>' block, similar to below: ''' using (IWebDriver driver = new ChromeDriver(...)) { // Use driver } ''' Reference: <URL>. I see that you are closing and quitting the browser, but you need to call '_driver.Dispose();' as well. The quick and easy way to accomplish this in your code is to call Dispose() after calling Quit(): ''' _driver.Close(); _driver.Quit(); _driver.Dispose(); // <-- this kills Chrome.exe return Json(response); ''' Or modify the method to wrap the use of '_driver' in a 'using(...)' statement: ''' [Route("/Test_SignIn")] public IActionResult Test_SignIn(string environment = "development") { string response = "Failed"; try { string outPutDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); // Your web driver is a LOCAL variable now, beware! using (IWebDriver driver = new ChromeDriver(outPutDirectory)) { if (environment == "production") { driver.Navigate().GoToUrl(productionUrl); } else { driver.Navigate().GoToUrl(developmentUrl); } By userNameFieldLocator = By.Id("AccountUserName"); WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30)); wait.Until(ExpectedConditions.ElementIsVisible(userNameFieldLocator)); _waitForLoaderToFinish(); IWebElement userNameField = driver.FindElement(userNameFieldLocator); IWebElement passwordField = driver.FindElement(By.Id("AccountPassword")); IWebElement signInButton = driver.FindElement(By.XPath("//button[contains(text(), 'Sign In')]")); userNameField.SendKeys(_username); passwordField.SendKeys(_password); signInButton.Click(); By dashboardLocator = By.Id("portalBanner_EmployeeName"); wait.Until(ExpectedConditions.ElementIsVisible(dashboardLocator)); IWebElement dashboard = driver.FindElement(dashboardLocator); response = "Success"; } } catch (Exception ex) { response = ex.Message; } return Json(response); } ''' Please note that your web driver becomes a now. It should not be a field on the class in order to prevent other methods from accessing this disposable resource.
21,426,947
1
21,426,975
<IMAGE> I have table as seen above and I want to create a custom array to pass values. Currently I am using the following lines of code: ''' var arr = $('input[type=text].editfield').map(function () { return this; }).get(); var objArr = jQuery.map(arr, function (i) { return { myDate: i.parentElement.previousSibling.previousSibling.previousSibling.previousSibling.previousSibling.previousSibling.childNodes[0].textContent, myValue: i.value } }).get(); ''' and I expect to have an array of objects of all items in my grid with Date and Value as properties respectively. But something is wrong and I can not solve. For example the code above says "" How can I correct my code to perform the correct action?
There is no need to use .get() on the static <URL> to get an array. --- Also there is no need to use 2 loops, ''' var objArr = $('input[type=text].editfield').map(function (idx, i) { //the element selection used here is cruel, if you can share the html used we can help you to clean it return { // you can try myDate: $(this).parent().prevAll().eq(5).text() - not testable without the html and what is the expected output myDate: i.parentElement.previousSibling.previousSibling.previousSibling.previousSibling.previousSibling.previousSibling.childNodes[0].textContent, myValue: i.value }; }).get(); '''
8,039,267
1
8,039,640
<URL>] Problem is that without text the boxes are placed 2 on each row, but with text the boxes appear under each other with spacing. To get the text in the boxes I used '<style>' in '<head>'. How can I FIX this annoying problem? IMAGE: <URL> <URL> Code: ''' <style> p { position:relative; top:-240px; left:180px; } h3 { position:relative; top:-270px; left:30px; } </style> ''' and ''' <div class="offers"> <div class="content_box"> <?php while($products = mysql_fetch_array($result)) { echo '<img src="includes/images/content_box.png" border=0/>'; // echo "<h3>" . $products['products'] . "</h3>"; // echo "<p>" . $products['description'] . "</p>"; } ?> </div> </div> ''' RESOLVED BY DOING: ''' <STYLE TYPE="text/css"> #title{color:red; padding-bottom: 240px; padding-left: 25px;} #desc{color:blue; padding-bottom: 135px; padding-left: 5px;} </STYLE> </head> ''' and ''' <div> <?php while($products = mysql_fetch_array($result)) {?> <table align="left" background="includes/images/box.gif" width="473" height="285"> <tr> <td width="35%" height="100%" id="title"> <?php echo $products['products'] . "&nbsp"; ?> </td> <td width="70%" height="100%" id="desc"> <?php echo $products['description'];?> </td> </tr> </table> <?php } ?> </div> </body> ''' This might be easy for some, but I'm new to this. Now working correctly. Thank you for giving me directions and Thank you Google and Stackoverflow for so much help =) <IMAGE>
I am asuming that content_box.png is the background for the box right? instead of including it in a create it in the background of a div with a class like this CSS: ''' .product_box { bacground:url(includes/images/content_box.png); width:xxxpx; /* the width of conrent_box.png */ height:xxxpx; /* the height of conrent_box.png */ position:relative; float:left; } ''' php: ''' <?php while($products = mysql_fetch_array($result)) { echo '<div class="product_box">'; // echo '<img src="includes/images/content_box.png" border=0/>'; echo "<h3>" . $products['products'] . "</h3>"; echo "<p>" . $products['description'] . "</p>"; echo '</div>'; } ?> ''' Hope it helps!
18,452,449
1
18,452,523
Here's a picture so you can understand what I want: <IMAGE> I have this green element already set up in my relative layout, and what I want is to put another element (the black one in the pic) above it so it gets centered exactly in the middle of the green element. Keep in mind that the black element doesn't have a constant width, and it's bigger in width than the green one. There are stuff like android:layout_alignLeft and android:layout_alignRight which would be helpful if I wanted it aligned left or right, but as far as I know there is no android:layout_alignCenter so I don't know how to do this thing...
As you said yourself, put both elements inside a . Then, set the "" property of both elements to true, and then set the "" property of the green element to the id of the black element. Here is the complete example: ''' <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <View android:id="@+id/view1" android:layout_width="100dp" android:layout_height="40dp" android:background="@color/Black" android:layout_centerHorizontal="true" android:layout_centerVertical="true" /> <View android:id="@+id/view2" android:layout_height="100dp" android:layout_below="@+id/view1" android:background="@color/Green" android:layout_centerHorizontal="true" /> </RelativeLayout> ''' ("center_vertical" is kinda optional) Or here, ''' <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <View android:id="@+id/view1" android:layout_width="100dp" android:layout_height="40dp" android:background="@color/Black" android:layout_centerVertical="true" /> <View android:id="@+id/view2" android:layout_width="40dp" android:layout_height="100dp" android:layout_below="@+id/view1" android:layout_alignLeft="@+id/view1" android:layout_alignRight="@+id/view1" android:layout_marginLeft="30dp" android:layout_marginRight="30dp" android:background="@color/Green" /> </RelativeLayout> ''' (In this case, the margins will define the second Views width) This is the end result: <IMAGE>
12,168,002
1
12,168,077
In my app, I use a 'UITableView' My problem is that I want to remove the last border of the last cell in 'UITableView'. Please check the following image: <IMAGE>
Updated on 9/14/15. My original answer become obsolete, but it is still a universal solution for all iOS versions: You can hide 'tableView''s standard separator line, and add your custom line at the top of each cell. The easiest way to add custom separator is to add simple 'UIView' of 1px height: ''' UIView* separatorLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, cell.bounds.size.width, 1)]; separatorLineView.backgroundColor = [UIColor grayColor]; [cell.contentView addSubview:separatorLineView]; ''' To date, I subscribe to <URL>: ''' self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero]; '''
22,187,329
1
22,187,577
I just started with vb.net so please be patient with me here. I'm working on an uni assignment where I need to build a small student registration program. I need to create a 7 digit student number whenever a user clicks register, my code and validation and connection to DB is working fine, 1. The student number should have 7 digits 2. The first two digits represent the year the student registers in (the last two digits of the full year) Which I get like this and it works fine: Dim cyear = DateTime.Now.ToString("yy") 3. Here is my problem: the next 4 numbers represents the number of students who have registered thus far, this number is always padded with 0 from the left to make up four digits. --- if 20 students have registered thus far (in 2014) then the next student will have student number 140021 --- 4 The last digit is a check digit which you get by summing the first 6 individual numbers of the student number, divide the result by 10 and take the remainder, and subtract the remainder by 10 to get last digit. , but what if only one student has registered thus far? Surely that cant produce a correct result (See Number 3 above) How do I generate numbers 3 to 6, padding from left to right incrementing with one with each new registration? I tried the following code but it is far off from working ''' 'Generate Student NR' Dim newstudent As Integer 'displays 1st 2 letter of current year for student number' Dim cyear = DateTime.Now.ToString("yy") Dim lastdigit As Double Dim lastdigitRemainder Dim studentnr As Integer 'if statment to generate new student number for each registration' If (register.Enabled = True) Then newstudent = cyear + 0 + 0 + 0 + 1 'generate last digit of student nr' lastdigit = (cyear + newstudent) / 10 lastdigitRemainder = lastdigit - 10 studentnr = lastdigit + lastdigitRemainder MsgBox(studentnr) ''' <IMAGE> Please note Im not asking for someone to complete this code for me, im just looking for a bit of advice, someone who can point me in the right direction etc. Also is the IF statment the correct selection structure I should use for the generation of the student number?
''' Dim intYear As Integer = TextBox1.Text 'The years last two digits' 'Show the student id: pad the students number with 0's, works with single, double etc digits. The intStudents is the variable I used for the student totals. MessageBox.Show(CStr(intYear.ToString) & intStudents.ToString("0000")) ''' A little more perferred way... ''' Dim strYear As String = TextBox1.Text MessageBox.Show(strYear & intStudents.ToString("D4")) 'D means the format and the number 4 is the length... ''' Your issue with your if that you have asked... ''' 'I assume this is your register button... if so you can do this.. If (register.Enabled) Then 'whatever else you need End If ''' Heres you full edited code... ''' 'Generate Student NR' Dim newstudent As String Dim cyear As String = DateTime.Now.ToString("yy") Dim studentTotal As Integer = 13 'However many students registered so far... 'if statment to generate new student number for each registration' If (register.Enabled = True) Then newstudent = cyear & studentTotal.ToString("D4") MessageBox.Show(newstudent) 'Use this as "MsgBox" is depreciated in newer frameworks' End If ''' 'Add one more to user variable...As you requested :) ''' Dim studentTotal As Integer = 13 'Put in your click event ... studentTotal = studentTotal += 1 '''
74,874,445
1
74,891,068
I have a state machine diagram for an application that has a UI and a thread that runs parallel. I model this using a state with 2 parallel regions. Now I want when that thread gives some message, for example an error, that the state of the UI changes, for example to an error screen state. I was wondering what the correct method to do this is, as I was not able to find any example of this situation online. The options that I thought of were creating a transition from every state to this error state when the error state is called, which in a big diagram would mean a lot of transitions. Or by just creating a transition from the thread to the error state (As shown in the image), which could possible be unclear. Example of second option <IMAGE>
You don't need a transition from every state. Just use a transition from the State 'State' to the 'Error window' state. It will then fire no matter what states are currently active. Such a transition will also leave the 'Some process' state. Since you didn't define initial states in the orthogonal regions, the right region of the state machine will then be in an undefined state. Some people allow this to happen, but for me it is not good practice. So, I suggest to add initial states to both regions. Then it is clear, which sub state will become active, when the 'State' state is entered for any reason. The fork would also not be necessary then. How you have done it in your example would also be Ok. However, since the 'Some process' state is left by this transition, this region is now in an undefined state. Again, the solution to this is to have an initial state here. I would only use such a transition between regions, when it contains more than one state and the 'On error' event shall not trigger a transition in all of the states. If the 'Some process' state is only there to allow for concurrent execution, there is an easier way to achieve this: The 'State' state can have a do behavior, that is running while the sub states are active. Orthogonal regions should be used wisely, since they add a lot complexity.
8,145,440
1
8,145,519
Instead of the traditional navigation, I am trying to emulate the terminal navigation, or how you navigate with vim. Example: ''' .. index otherfile ''' This is my code: ''' $dir = realpath(dirname(__FILE__)); if(is_dir($dir)){ if($open = opendir($dir)){ while(($file = readdir($open)) !==false){ if(is_dir($file)){ if($file == '.'){ } else{ echo "<a href=".$file.">".$file."</a><br/>"; } } else{ $name = explode('.php',$file); echo "<a href=".$file.">".$name[0]."</a><br/>"; } } } } else{ echo $dir." Was not found"; } } ''' 1. How can I remove the file or folder I am in from the list? For example, if I am on the page index.php, it is still appearing on the list. 2. I want to sort files by given them a number example '1file.php' '2anotherfile.php'.. How could I sort them by the number, then remove the number and '.php', and finally print it out? If you feel like refactoring something please do so... <IMAGE>
1. "How can I remove the file or folder I am in from the list? For example, if I am on the page index.php, it is still appearing on the list." Just check if the current item is the current file, if it is then skip it: ''' else { if ($name == basename(dirname(__FILE__))) continue; // if this is the current file, go to the next iteration of the loop $name = explode('.php',$file); echo "<a href=".$file.">".$name[0]."</a><br/>"; } ''' Note that this assumes you are in the same directory as the file (which it can do because '$dir' is always the directory the script is in), if not you can just add a directory check as well. 1. "How can add a number to the start of the file or folder, example 1index.php, then on the code, organize all the files and folder by number, and print them without the number and '.php'?" Well I'm not too sure what you mean by this, but if you mean sort alphabetically, then it is already alphabetically sorted when you get the list.
67,318,419
1
67,323,666
I've been trying to scrape <URL> using rvest and selectorGadge. I am able to scrape the product description, but when I try to get the values as shown in the picture: <IMAGE> However, when I run the code: ''' library(dplyr) library(rvest) read_html("https://www.dicasanet.com.br/material-de-construcao") %>% html_nodes(".product-payment") ''' I keep getting the result "{xml_nodeset (0)}". I noticed that, unlike other values (like the name of the product), this is not a div.a, but a div.div instead. Is there another way to get these values? How should I proceed? Thanks in advance!
Data is dynamically loaded from a JavaScript object within a 'script' tag. You can regex that out from the response text, parse with 'jsonlite' into a json object and then extract what you want for the products ''' library(magrittr) library(rvest) library(stringr) library(jsonlite) page <- read_html('https://www.dicasanet.com.br/loja/catalogo.php?loja=790930&categoria=1') data <- page %>% toString() %>% stringr::str_match('dataLayer = (\[.*\])') %>% .[2] %>% jsonlite::parse_json() print(data[[1]]$listProducts) '''
48,516,763
1
48,516,963
<IMAGE> I need to get all the users count from superuser and list those in a table view with there details. Is there a code to directly get the count of documents inside a collection, other than using functions inside firebase console. Or a Simple Query to traverse through the documents!
this will collect all the document for a collection and print them ''' db.collection("superUsers").getDocuments() { (querySnapshot, err) in if let err = err { print("Error getting documents: \(err)"); } else { var count = 0 for document in querySnapshot!.documents { count += 1 print("\(document.documentID) => \(document.data())"); } print("Count = \(count)"); } } '''
23,960,007
1
23,960,131
I'm using Inkscape to convert images from PDF to SVG using the following code: ''' internal static void ConvertImageWithInkscapeToLocation(string baseImagePath, string newImagePath, bool crop = true) { InkscapeAction(string.Format("-f "{0}" -l "{1}"", baseImagePath, newImagePath)); } internal static void InkscapeAction(string inkscapeArgs) { Process inkscape = null; try { ProcessStartInfo si = new ProcessStartInfo(); inkscape = new Process(); si.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; si.FileName = inkscapePath; // the path to Inkscape.exe, defined elsewhere si.Arguments = inkscapeArgs; si.CreateNoWindow = true; inkscape.StartInfo = si; inkscape.Start(); } finally { inkscape.WaitForExit(); } } ''' It's a fairly straightforward "launch app with arguments, wait for close" set up and it works well; the only problem is that on slower machines, the image conversion process (and presumably the 'inkscape.WaitForExit()') takes too long and this dialog message is displayed: <IMAGE> Clicking on "Switch to..." pops up the Windows Start Menu (I'm guessing because I'm hiding the process); "Retry" will bring the message back up over and over again until the process finishes.
There are some ways to do it: 1-A dirty cheap way is to wait with a timeout (WaitForExit(timeout)), do a DoEvents (I assume you are doing it in a winforms app in the main thread), check if process finished and loop until it: ''' finally { while(!inkScape.HasExited) { inkscape.WaitForExit(500); Application.DoEvents(); } } ''' 2-The right way is to do it in another thread and then signal your main program to continue ''' ThreadPool.QueueUserWorkItem((state) => { ConvertImageWithInkscapeToLocation... }); ''' If you do it in another thread remember CrossThreadException, don't update the UI from the thread.
26,156,701
1
26,173,900
It appears that AutoLayout is not finding my top neighbor (Grand Pu Bah). What do you recommend doing to visually set the top constraint to that of the top neighbor vs. the current view. <IMAGE>
I think the image overlaps with Grand Pu Bah which is causing Auto Layout to not allow Grand Pu Bah as an option. If you move the image further down, you should see Grand Pu Bah as an option. Then tweak the constant (you can select 0, or even negative number for overlap) in the constraint to make the image closer.
28,503,653
1
28,504,617
So I have two sortable lists that a user can drag items out of and into a third list where they can hopefully export that list to a downloadable csv file. I have the multiple selectable and sortable part working fine at this <URL>, but now need to include the export to csv funtionality. Can anyone help? Here is a screenshot of what I am attempting to achieve from the <URL>: <IMAGE> Here is my code so far: ''' <html> <meta charset="utf-8" /> <title>jQuery UI Sortable with Selectable</title> <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" /> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> $(function() { // $('body').selectable({ filter: 'li' //filter: '#album2 > li' }); $('.connectedSortable').sortable({ connectWith: ".connectedSortable", delay: 100, start: function(e, ui) { var topleft = 0; // if the current sorting LI is not selected, select $(ui.item).addClass('ui-selected'); $('.ui-selected div').each(function() { // save reference to original parent var originalParent = $(this).parent()[0]; $(this).data('origin', originalParent); // position each DIV in cascade $(this).css('position', 'absolute'); $(this).css('top', topleft); $(this).css('left', topleft); topleft += 20; }).appendTo(ui.item); // glue them all inside current sorting LI }, stop: function(e, ui) { $(ui.item).children().each(function() { // restore all the DIVs in the sorting LI to their original parents var originalParent = $(this).data('origin'); $(this).appendTo(originalParent); // remove the cascade positioning $(this).css('position', ''); $(this).css('top', ''); $(this).css('left', ''); }); // put the selected LIs after the just-dropped sorting LI $('#album .ui-selected').insertAfter(ui.item); // put the selected LIs after the just-dropped sorting LI $('#album2 .ui-selected').insertAfter(ui.item); } }); // }); <style> *, *:before, *:after { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } #album { list-style: none; float: left; width: 20%; border: 1px solid blue; } #album2 { list-style: none; float: left; width: 20%; border: 1px solid blue; } #album li { float: left; margin: 5px; } #album2 li { float: left; margin: 5px; } #album div { width: 100px; height: 100px; border: 1px solid #CCC; background: #F6F6F6; } #album2 div { width: 100px; height: 100px; border: 1px solid #CCC; background: #F6F6F6; } #album .ui-sortable-placeholder { border: 1px dashed #CCC; width: 100px; height: 100px; background: none; visibility: visible !important; } #album2 .ui-sortable-placeholder { border: 1px dashed #CCC; width: 100px; height: 100px; background: none; visibility: visible !important; } #album .ui-selecting div, #album .ui-selected div { background-color: #3C6; } #album2 .ui-selecting div, #album2 .ui-selected div { background-color: #3C6; } #anotheralbum { list-style: none; float: left; width: 20%; height: 800px; border: 1px solid green; } </style> <body> <ul id="album" class="connectedSortable"> <li id="li1"><div>1- First</div></li> <li id="li2"><div>2- Second</div></li> <li id="li3"><div>3- Third</div></li> <li id="li4"><div>4- Fourth</div></li> <li id="li5"><div>5- Fifth</div></li> <li id="li6"><div>6- Sixth</div></li> <li id="li7"><div>7- Seventh</div></li> <li id="li8"><div>8- Eighth</div></li> </ul> <ul id="album2" class="connectedSortable"> <li id="li1"><div>1- 1</div></li> <li id="li2"><div>2- 2</div></li> <li id="li3"><div>3- 3</div></li> <li id="li4"><div>4- 4</div></li> <li id="li5"><div>5- 5</div></li> <li id="li6"><div>6- 6</div></li> <li id="li7"><div>7- 7</div></li> <li id="li8"><div>8- 8</div></li> </ul> <div id="anotheralbum" class="connectedSortable"> This is a list of what to export to csv </div> <br style="clear:both"> </body> </html> '''
The biggest problem is detecting browser support. If you need it to work x-browser you want to know which browsers support the 'download' attribute. There's your biggest issue right there: in order to detect it, you fall back to a dynamic iframe which holds the data. IE has a data url limit and actually only supports it for images. In short, false positives occur and for those who support it, will trigger the download immediately. That said, I don't believe you can do it x-browser without detecting the useragent. ''' function addDataUri(){ var csvData = convertJsonToCsv('<%= JsonResults %>'), dataUri = 'data:text/csv;charset=utf-8,' + escape(csvData), exportLink = $('.exportLink a'); if (exportLink.length) { // if browser is unsupported, fallback to flash if (isIe()) { getDownloadify(function () { setupDownloadify(csvData, exportLink); }); } else { exportLink.prop({ href: dataUri, target: '_blank', download: 'export_' + +(new Date()) + '.csv' }); } } } function convertJsonToCsv(json) { var objArray = json, array = JSON.parse(objArray), str = '', line, i = 0; for (; i < array.length; i++) { line = ''; for (var index in array[i]) { line += array[i][index] + ','; } line.slice(0, line.length - 1); str += line + ' '; } return str; } ''' So in your example the 'convertJsonToCsv()' should be different. As stated in the comments, something along the lines of: ''' function convertJQueryToCsv(){ var arr = []; $.each($yourObj, function(){ arr.push($(this).text()); }); return arr.join(','); } ''' If you're interested in how I set up the flash fallback, let me know.
26,352,797
1
26,903,225
I have a UIDatePicker in a TableView with Static Cells. The DatePicker works perfectly in iPhone version of App, but the iPad seems to compress the DatePicker so that the center column that holds the day of the month (dd) does not display. Notice that the "er" in "November" is truncated. I verified this by changing the date style to Spanish (dd MMMM YYY) and the date displays as does the first half of the month and all of the year. The last half of each month's name is truncated. Has anyone encountered a problem like this in porting over to iOS 8? Never sure how much code to post. Here is most everything in the relevant class ''' @property (strong, nonatomic) IBOutlet UITableViewCell *dateDisplay; @property (strong, nonatomic) IBOutlet UITableViewCell *datePickerCell; @property (strong, nonatomic) IBOutlet UIDatePicker *datePicker; @property (strong, nonatomic) IBOutlet UITableViewCell *unattached; @property (strong, nonatomic) IBOutlet UITableViewCell *middleschool; @property (strong, nonatomic) IBOutlet UITableViewCell *highschool; @property (strong, nonatomic) IBOutlet UITableViewCell *collegiate; @property (strong, nonatomic) IBOutlet UITableViewCell *youthclub; @end @implementation MeetFinderTableViewController @synthesize divisions = _divisions; @synthesize datePickerIndexPath = _datePickerIndexPath; @synthesize meetDate = _meetDate; @synthesize doSaveUserDefaults = _doSaveUserDefaults; @synthesize divisionSelected = _divisionSelected; @synthesize arrayOfReuseIds = _arrayOfReuseIds; @synthesize myTV = _myTV; # pragma SplitViewController Variables @synthesize meetIDForSegue = _meetIDForSegue; @synthesize meetNameForSegue = _meetNameForSegue; #pragma SetUp Configuration -(void) setArrayOfReuseIds:(NSArray *)arrayOfReuseIds { _arrayOfReuseIds = arrayOfReuseIds; } -(void) setMyTV:(UITableView *)myTV { _myTV = myTV; } -(void) setMeetDate:(NSDate *)meetDate { if(_meetDate != meetDate){ _meetDate = meetDate; [self setDoSaveUserDefaults:YES]; } } - (id)initWithStyle:(UITableViewStyle)style { self = [super initWithStyle:style]; if (self) { // Custom initialization } return self; } - (MapViewController *)splitViewMapViewController { id mvc = [self.splitViewController.viewControllers lastObject]; if (![mvc isKindOfClass:[MapViewController class]]) { mvc = nil; } if (debug==1) NSLog(@"%@ = %@",NSStringFromSelector(_cmd), mvc); return mvc; } - (void)awakeFromNib { [super awakeFromNib]; self.splitViewController.delegate = self; if (debug==1) NSLog(@"Do I make it to %@",NSStringFromSelector(_cmd)); } - (void)viewDidLoad { [super viewDidLoad]; self.clearsSelectionOnViewWillAppear = YES; self.datePicker.hidden = YES; self.datePickerIsShowing = NO; [self setArrayOfReuseIds:[[NSArray alloc] initWithObjects: @"unattached",@"middleschool",@"highschool",@"collegiate",@"youthclub", nil]]; [self setDivisions:[[NSArray alloc] initWithObjects: @"Unattached", @"Middle School", @"High School", @"Collegiate", @"Youth Club", nil]]; if ([[NSUserDefaults standardUserDefaults] objectForKey:@"divisionPreference"]) { [self setDivisionSelected:[[NSUserDefaults standardUserDefaults] objectForKey:@"divisionPreference"]]; } else [self setDivisionSelected:[NSNumber numberWithInt:highSchoolTag]]; if ([[NSUserDefaults standardUserDefaults] objectForKey:@"datePreferenceForMeetSearch"]) { [self setMeetDate:[[NSUserDefaults standardUserDefaults] objectForKey:@"datePreferenceForMeetSearch"]]; } else [self setMeetDate:[NSDate date]]; [self setMyTV:self.tableView]; if (debug==1) NSLog(@"In %@ before check splitViewMapViewController",NSStringFromSelector(_cmd)); if ([self splitViewMapViewController]) { // if in split view [self splitViewMapViewController].dateForSearch = self.meetDate; [self splitViewMapViewController].levelOfCompetition = [self.divisionSelected stringValue]; } } -(void) viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self setupDateLabel]; [self setUpMenuItems]; if (debug==1) NSLog(@"Do I make it to %@",NSStringFromSelector(_cmd)); } -(void) viewWillDisappear:(BOOL)animated { [super viewWillDisappear:YES]; if (self.doSaveUserDefaults) { NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; [userDefaults setObject:self.divisionSelected forKey:@"divisionPreference"]; [userDefaults setObject:self.meetDate forKey:@"datePreferenceForMeetSearch"]; [userDefaults synchronize]; NSLog(@"Getting ready to set newPreferences with divisionSelected: %@ and dateOfMeet: %@", [self.divisionSelected stringValue], self.meetDate); MapPreferencesDataDelegate *newPreferences = [[MapPreferencesDataDelegate alloc] initWithName:[self.divisionSelected stringValue] dateOfMeet:self.meetDate]; [self.delegate saveMeetSearchPreferences:newPreferences]; } } - (void)setupDateLabel { self.dateFormatter = [[NSDateFormatter alloc] init]; [self.dateFormatter setDateStyle:NSDateFormatterMediumStyle]; [self.dateFormatter setTimeStyle:NSDateFormatterNoStyle]; NSDate *defaultDate; if (!self.meetDate || self.meetDate == nil) { defaultDate = [NSDate date]; [self setMeetDate:defaultDate]; } else defaultDate = self.meetDate; self.dateDisplay.textLabel.text = [NSString stringWithFormat:@"%@",stringForDateDisplay]; self.dateDisplay.textLabel.textColor = [self.tableView tintColor]; self.dateDisplay.detailTextLabel.text = [self.dateFormatter stringFromDate:defaultDate]; self.dateDisplay.detailTextLabel.textColor = [self.tableView tintColor]; } - (void)showDatePickerCell { self.datePickerIsShowing = YES; [self.tableView beginUpdates]; [self.tableView endUpdates]; self.datePicker.hidden = NO; self.datePicker.alpha = 0.0f; [UIView animateWithDuration:0.25 animations:^{ self.datePicker.alpha = 1.0f; }]; } - (void)hideDatePickerCell { self.datePickerIsShowing = NO; [self.tableView beginUpdates]; [self.tableView endUpdates]; [UIView animateWithDuration:0.25 animations:^{ self.datePicker.alpha = 0.0f; } completion:^(BOOL finished){ self.datePicker.hidden = YES; }]; } -(void) placeCheckMarkForDivisionSelection:(NSInteger) myDivisionPreference #pragma mark - Table view data source -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { switch (indexPath.section) { case 0: { if (indexPath.row == 0){ self.datePicker.hidden = NO; self.datePickerIsShowing = !self.datePickerIsShowing; [UIView animateWithDuration:.4 animations:^{ [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade]; [self.tableView reloadData]; }]; } break; } case 1: { UITableViewCell *cell1 = [tableView cellForRowAtIndexPath:indexPath]; NSInteger tagForSelectedDivision = cell1.tag; [self placeCheckMarkForDivisionSelection:tagForSelectedDivision]; // [self setDivisionSelected:[NSNumber numberWithInteger:tagForSelectedDivision]]; if ([self splitViewMapViewController]) [self splitViewMapViewController].levelOfCompetition = [self.divisionSelected stringValue]; break; } } [self.tableView deselectRowAtIndexPath:indexPath animated:YES]; } -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { if (indexPath.section == 0 && indexPath.row == 1) { // this is my picker cell if (self.datePickerIsShowing) { return 219; } else { return 0; } } else { return self.tableView.rowHeight; } } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return numberOfSections; } #pragma mark - Action methods - (IBAction)pickerDateChanged:(UIDatePicker *)sender { if ([self splitViewMapViewController]) { // if in split view [self splitViewMapViewController].dateForSearch = sender.date; [self splitViewMapViewController].levelOfCompetition = [self.divisionSelected stringValue]; } self.dateDisplay.detailTextLabel.text = [self.dateFormatter stringFromDate:sender.date]; self.meetDate = sender.date; [self setMeetDate:sender.date]; } - (void) displayAlertBoxWithTitle:(NSString*)title message:(NSString*) myMessage cancelButton:(NSString*) cancelText { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:myMessage delegate:nil cancelButtonTitle:cancelText otherButtonTitles:nil]; [alert show]; } #pragma SplitViewController Implementation - (id <SplitViewBarButtonItemPresenter>)splitViewBarButtonItemPresenter { id detailVC = [self.splitViewController.viewControllers lastObject]; if (![detailVC conformsToProtocol:@protocol(SplitViewBarButtonItemPresenter)]) { detailVC = nil; } return detailVC; } - (BOOL)splitViewController:(UISplitViewController *)svc shouldHideViewController:(UIViewController *)vc inOrientation:(UIInterfaceOrientation)orientation { return NO; } - (void)splitViewController:(UISplitViewController *)svc willHideViewController:(UIViewController *)aViewController withBarButtonItem:(UIBarButtonItem *)barButtonItem forPopoverController:(UIPopoverController *)pc { barButtonItem.title = barButtonItemTitle; [self splitViewBarButtonItemPresenter].splitViewBarButtonItem = barButtonItem; } - (void)splitViewController:(UISplitViewController *)svc willShowViewController:(UIViewController *)aViewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem { [self splitViewBarButtonItemPresenter].splitViewBarButtonItem = nil; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return YES; } @end ''' Thanks, <IMAGE>
The problem seems to be associated with Autolayout. Please select the date picker in storyboard and add "Center Horizontly in container" constraint with UITableViewCell's content view. See the attached image for better understanding. <IMAGE> Required result after applying constraint; <IMAGE> Without Constraints; <IMAGE> To add constraint, right click on the UIDatePicker while holding and drag the pointer to UITableViewCell's content view and release the pointer. Now select the "Center Horizontly in container" constraint. Please try and post in comments.
23,696,138
1
23,697,021
Can I join one system with component of second subsystem by dependency ? My intence is to show that in my system(system 2) is module / component called subsystem 1 and external system uses this subsystem. <IMAGE> Is this correct? Interfaces aren't defined now, so I can only show that dependency.
Let me interpret this diagram and the answer should come naturally. :) "System 1" depends on "Subsystem 1" in some way. "System 1" does not know anything about the "System 2", that contains the "Subsystem 1". This means that "System 1" somehow gets the direct access to "Subsystem 1", with no contact with "System 2". Is this correct? That's the answer to your question. :)
26,504,593
1
26,506,868
I have a project for my C# module where I want to make a booking system for the AULA(see picture below). I want the user to be able to click on a seat that has to be booked. I can do this with normal pictureboxes or datagridviews, but this would not be curved like the seats on the side. Is it possible for me to rotate components in any degrees I choose or is there a better way for me to do this? <IMAGE>
I have been using this <URL> in the past. You just need to provide the background image and a collection of polygons representing clickable areas. Those are internally added to a 'GraphicsPath' searchable by the use of markers. The 'GraphicsPath.IsVisible' method is used to detect whether the click point is interior to a certain area.
26,535,258
1
26,535,606
Is there a way to trim letters of a string? Or Convert a string to an integer removing its letters from it? Story: I have in which I have bunch of options on an application and all of them add up points depending on the option selected by the user. I gave them values like hsq2 hsq4 hsq6 and now I need to be able to get the one that is selected and remove letters from it and add up values. If you know a better way of doing this please let me know also.. <IMAGE>
The better way would be to use 'XAML' and databinding to a rich ViewModel that has separate properties for each item's label and its score value as an integer. Then a method on your ViewModel would perform the sum of selected values and return it for data binding to the Total Score display. Search for MVVM if you want to know more about that approach. However, since it looks like you're building a WinForms app, you could use the Tag property of each element to store the integer value. That's how I would have done it 7 years ago.
8,854,388
1
8,855,678
I have basic knowledge of CSS. Using overflow isnt really ideal. Scroll bars are specific to the div, rather than the browser. So displaying on phones is a problem.(especially the iPhone which disables the scroll leaving content unaccessable). Having overflow on visible is shown in the image, and obviously hidden isnt what i want. So, is it possible to have the main div (white area) expand to contain the div rather than cause an overflow. The white part currently stops on the screen edge (before scrolling) Take Stackoverflow for example. Its centered. and only when you cant contain it, does it go offscreen. But u simply scroll right to see the rest. I would much prefer mine centred too. if anyone has an knowledge of how to achieve this, please let me know. The basic concept at the moment is ''' <div id="main"> <div id="sidebar"></div> <div id="body"></div> </div> ''' <IMAGE> This is ASP.NET MVC 3
This is indeed quite tricky to achieve because there is no CSS way to resize parent elements according to their children's content, and also in JavaScript it's not straight-forward. There is a solution though with jQuery using <URL>. Basically the mini-script creates a span around your text and measures its width. You can then use it to resize your container: ''' <script type="text/javascript"> $(function() { //define the mini-function to measure text $.fn.textWidth = function(){ var html_org = $(this).html(); var html_calc = '<span>' + html_org + '</span>' $(this).html(html_calc); var width = $(this).find('span:first').width(); $(this).html(html_org); return width; }; //now resize your main container according to the body width. $("#main").css("width", $("#body").textWidth()); //this would be body + sidebar // $("#main").css("width", $("#body").textWidth()+$("#sidebar").textWidth()); }); </script> ''' Solution to your problem in jsfiddle: <URL>
29,085,582
1
29,085,618
In the formula bar the data shows up as '69.849999999' and in the cell as '69.85'. I am trying to get that number in the formula bar as '69.85'. I tried Copy and Paste Values and almost everything else that I can think of. Even formatting the cell as a number with only two decimal places. Nothing is working. Any ideas? <IMAGE>
Try: ''' =ROUND(A1,2) ''' then select, Copy, Paste Special, Values.
27,593,430
1
27,597,444
I would like the red button to be animated towards the leading position of the second button : <IMAGE> Some examples showed how to change the "constant" with numbers, but I would like to put automatically at the leading position of the second button. I tried this, but the red button does not move, the animations log is correctly called though : ''' - (void)updateConstr{ NSLayoutConstraint *newLeading = [NSLayoutConstraint constraintWithItem:self.redB attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.secondButton attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0.0f]; self.leadingConstraint = newLeading;//is an IBOutlet pointing on the constraint (see the image) [self.redB setNeedsUpdateConstraints]; [UIView animateWithDuration:0.5 animations:^{ [self.redB layoutIfNeeded]; NSLog(@"animations");//is called, but the red button does not move }]; } - (IBAction)firstAction:(id)sender { //after a click on button "one" NSLog(@"firstAction"); [self updateConstr]; } '''
This must do it: ''' - (void)updateConstr{ NSLayoutConstraint *newLeading = [NSLayoutConstraint constraintWithItem:self.redB attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.secondButton attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0.0f]; [self.redB.superview removeConstraint: self.leadingConstraint]; [self.redB.superview addConstraint: newLeading]; self.leadingConstraint = newLeading; [UIView animateWithDuration:0.5 animations:^{ [self.redB layoutIfNeeded]; }]; } '''
6,348,992
1
6,350,961
In Excel, if you import whitespace delineated text in which the columns do not line up perfectly and data may be missing, like ''' pH pKa/Em n(slope) 1000*chi2 vdw0 CYS-I0014_ >14.0 0.00 LYS+I0013_ 11.827 0.781 0.440 0.18 ''' you are given the option to treat it as fixed width columns, and Excel can figure out the column widths automatically, usually with pretty good results. Is there a library in Python which can break up poorly formated fixed-width text in a similarly automatic fashion? This is what the fixed width text import looks like in Excel. In step one, you just check the 'fixed-width' radio button, and then here in step two Excel has already added in column breaks automatically. The only time it fails to do so properly is when there is not at least one whitespace character overlapping in each column break in each line. <IMAGE>
First off, Excel (2003, at home) isn't quite so smart. If your column 1000*chi2 contains spaces, e.g. 1000 * chi2, excel will guess wrong. Trivial case: if your data was originally separated by tabs (not spaces), and multiple tabs were used to indicate empty columns, then, at least in TCL, it's easy to split each line by tab content, and I guess trivial too in Python. But I'm guessing your problem is that they've used space characters only. The biggest clue I see to solving this one was to paste your text into notepad and choose a fixed size font. Everything lines up neatly, and you can use the number of characters in each line as a measure of "length". So, IF you can rely on this feature of your input, then you can use a "sieve" approach to identifying where the column breaks are automatically. As you munch through the lines in a first pass, note the "positions" along the line that are occupied by non white-space, eliminating a position from your list if it's EVER occupied by non white space. As you go, you'll quickly arrive at a set of positions that are NEVER occupied by non white space. These, then, are your column dividers. In your example, your "sieve" would end up with positions 10-16, 23-24,32, 42-47 never occupied by non whitespace (assuming I can count). Thus the complement of that set is your set of column positions in which your data must lie. So, foreach line, each block of nonwhitespace will fit into exacly one of your columns from the set of positions (i.e the complement set) identified above. I've never coded in Python, so attached is a TCL script that will identify,using the sieve approach, where the column breaks are in the text, and emit a new text file with exactly those space characters replaced by a single tab - ie. 10-16 replaced by one tab, 23-24 by another, etc. The resulting file is tab-separated, i.e. the trivial case. I confess I've only tried it on YOUR little case data, copied into a text file called ex.txt; output goes to ex_.txt. I suspect it also might have problems if headings contain spaces. Hope this helps! ''' set fh [open ex.txt] set contents [read $fh];#ok for small-to-medium files. close $fh #first pass set occupied {} set lines [split $contents ];#split contents at line breaks. foreach line $lines { set chrs [split $line {}];#split each line into chars. set pos 0 foreach chr $chrs { if {$chr ne " "} { lappend occupied $pos } incr pos } } #drop out with long list of occupied "positions": sort to create #our sieve. set datacols [lsort -unique -integer $occupied] puts "occupied: $datacols" #identify column boundaries. set colset {} set start [lindex $datacols 0];#first occupied pos might be > 0?? foreach index $datacols { if {$start < $index} { set end $index;incr end -1 lappend colset [list $start $end] puts "col break starts at $start, ends at $end";#some instro! set start $index } incr start } #Now convert input file to trivial case output file, replacing #sieved space chars with tab characters. set tesloc [lreverse $colset];#reverse the column list! set fh [open ex_.txt w] foreach line $lines { foreach ele $tesloc { set line [string replace $line [lindex $ele 0] [lindex $ele 1] " " ] } puts "newline is $line" puts $fh $line } close $fh '''
17,667,023
1
17,667,057
I reset my local master to a commit by this command: ''' git reset --hard e3f1e37 ''' when I enter '$ git status' command, terminal says: ''' # On branch master # Your branch is behind 'origin/master' by 7 commits, and can be fast-forwarded. # (use "git pull" to update your local branch) # nothing to commit, working directory clean ''' Since I want to reset origin/header as well, I checkout to origin/master: ''' $ git checkout origin/master Note: checking out 'origin/master'. You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by performing another checkout. If you want to create a new branch to retain commits you create, you may do so (now or later) by using -b with the checkout command again. Example: git checkout -b new_branch_name HEAD is now at 2aef1de... master problem fixed for master. its okay now. ''' and reset the header by this command: ''' $ git reset --hard e3f1e37 HEAD is now at e3f1e37 development version code incremented for new build. ''' Then I tried to add commit to origin/header that I was not successful. ''' $ git commit -m "Reverting to the state of the project at e3f1e37" # HEAD detached from origin/master nothing to commit, working directory clean ''' Finally, I checkout to my local master. ''' $ git checkout master Switched to branch 'master' Your branch is behind 'origin/master' by 7 commits, and can be fast-forwarded. (use "git pull" to update your local branch) ''' Since, I reset the head of origin/master I expect local and origin should be in same direction but as you see, git is saying that my local/master is behind origin/master by 7 commits. How can I fix this issue? The things that I'm looking for is Head of local/master and origin/master point to same commit. Following image shows what I did. Thanks. <IMAGE>
'origin/xxx' branches are always pointer to a remote. You cannot check them out as they're not pointer to your local repository (you only checkout the commit. That's why you won't see the name written in the command line interface branch marker, only the commit hash). What you need to do to update the remote is to force push your local changes to master: ''' git checkout master git reset --hard e3f1e37 git push --force origin master # Then to prove it (it won't print any diff) git diff master..origin/master '''
27,996,775
1
28,019,855
So I have an invoice and a credit memo, and the two are linked via a payment as per <URL>. All is good, the invoice is showing as paid and the customer's balance is correct. If I open up the credit memo (Adjustment Note) in the GUI I am able to see at a glance the related payment at the right side of the screen: <IMAGE> Now, I am trying to read back this information from the QBO IPP API (v3). Querying for the adjustment note I get the following response. As you can see, there is nothing there to tell me about this linked payment: ''' <CreditMemo domain="QBO" sparse="false"> <Id>1239</Id> <SyncToken>1</SyncToken> <MetaData> <CreateTime>2015-01-15T09:17:07-08:00</CreateTime> <LastUpdatedTime>2015-01-15T09:17:09-08:00</LastUpdatedTime> </MetaData> <DocNumber>4109</DocNumber> <TxnDate>2014-12-02</TxnDate> <CurrencyRef name="Australian Dollar">AUD</CurrencyRef> <PrivateNote>Cancelled</PrivateNote> <Line> <Id>1</Id> <LineNum>1</LineNum> <Amount>318.18</Amount> <DetailType>SalesItemLineDetail</DetailType> <SalesItemLineDetail> <ItemRef name="IPP">10</ItemRef> <TaxCodeRef>10</TaxCodeRef> </SalesItemLineDetail> </Line> <Line> <Amount>318.18</Amount> <DetailType>SubTotalLineDetail</DetailType> <SubTotalLineDetail /> </Line> <TxnTaxDetail> <TotalTax>31.82</TotalTax> <TaxLine> <Amount>31.82</Amount> <DetailType>TaxLineDetail</DetailType> <TaxLineDetail> <TaxRateRef>20</TaxRateRef> <PercentBased>true</PercentBased> <TaxPercent>10</TaxPercent> <NetAmountTaxable>318.18</NetAmountTaxable> </TaxLineDetail> </TaxLine> </TxnTaxDetail> <CustomerRef name="xxxxxx">99</CustomerRef> <GlobalTaxCalculation>TaxInclusive</GlobalTaxCalculation> <TotalAmt>350.00</TotalAmt> <PrintStatus>NeedToPrint</PrintStatus> <EmailStatus>NotSet</EmailStatus> <Balance>0</Balance> <RemainingCredit>0</RemainingCredit> </CreditMemo> ''' If I read the payment I can learn about this adjustment note and the invoice from 'Line.LinkedTxn': ''' <Line> <Amount>350.00</Amount> <LinkedTxn> <TxnId>1190</TxnId> <TxnType>Invoice</TxnType> </LinkedTxn> <LineEx> <NameValue> <Name>txnId</Name> <Value>1190</Value> </NameValue> <NameValue> <Name>txnOpenBalance</Name> <Value>350.00</Value> </NameValue> <NameValue> <Name>txnReferenceNumber</Name> <Value>4069</Value> </NameValue> </LineEx> </Line> <Line> <Amount>350.00</Amount> <LinkedTxn> <TxnId>1239</TxnId> <TxnType>CreditMemo</TxnType> </LinkedTxn> <LineEx> <NameValue> <Name>txnId</Name> <Value>1239</Value> </NameValue> <NameValue> <Name>txnOpenBalance</Name> <Value>350.00</Value> </NameValue> <NameValue> <Name>txnReferenceNumber</Name> <Value>4109</Value> </NameValue> </LineEx> </Line> ''' If I read the invoice I can learn about the payment from 'LinkedTxn': ''' <LinkedTxn> <TxnId>1240</TxnId> <TxnType>Payment</TxnType> </LinkedTxn> ''' But I need to find the payment given the adjustment note. As far as I can tell from the documentation, there is no way to query payments for their lines' contents. So, how do I find this payment given the credit memo, so I can learn what it is paying?
Credit Memo, Invoice and Payment all apply to same CustomerRef. Credit memo does not support the linked txn details yet, so as a workaround, you can try this- Get the Payment/s which have same customerref as creditmemo's customeref. Then loop through the payment/s to read the linked txn ids and match it against the credit memo id you have. Not a great solution but since your use is not supported by the V3 api right now, you can try the above.
71,964,043
1
71,968,943
I want to place text at the bottom of a card and blur the text area with a translucent color. This is what I have so far. The design I am trying to achieve is this. (Collection Area with cards specific part) <IMAGE> Here's my code: ''' @Composable fun CollectionCardArea( collection: Collection, cardWidth: Dp ) { Card( modifier = Modifier .width(cardWidth) .padding(start = 2.dp, end = 25.dp, bottom = 5.dp, top = 0.dp) .clickable { }, shape = RoundedCornerShape(6), elevation = 4.dp ) { Box(modifier = Modifier .fillMaxSize(), ) { Image( painter = rememberImagePainter( data = collection.image ), contentDescription = collection.name, contentScale = ContentScale.Crop, modifier = Modifier .fillMaxSize() ) } Box(modifier = Modifier .fillMaxWidth() .height(20.dp) .background(Color.Transparent) ) { Text(text = collection.name, color = Color.White) } } } ''' The problem is I cannot find a way to align the text to the bottom of the screen. Also, I cannot figure out how to blur the text area.
First thing, Card can't position its own child (when there are multiple children). So you need to use something like 'Column', 'Row', 'Box', or else inside the card itself. So instead having a tree like this ''' - Card - Box - Image - Box - Text ''' You can try it like this ''' - Card - Box - Box - Image - Box - Text ''' Second, as for the blur in Jetpack-Compose you can refer to this <URL>. But the API itself is only available on Android 12 and up.
22,348,835
1
25,794,440
I have a screen full of code that displays for about half a second on loading some pages in chrome. I managed to grab a <URL> of it. I think this one is from a google search for the London tube map. <IMAGE> I have disabled chrome extensions and antivirus but it still appears. Does anyone know what this is?
In this particular instance the code is generated by <URL>. If the antivirus is installed, the extension seems to be enabled without being displayed in Chrome's list of extensions. Disabling the antivirus doesn't seem to disable the extension. But you can clearly see it is activated in a google search as each link has a specific icon next to it.<IMAGE> Other extensions might do a similar thing, but in the lower-left part of the screenshot, the code is: ''' fraud_link = "http://trafficlight.bitdefender.com/info?url={URL}&language=en_US"; ''' Which makes it obvious this extention is causing the code to be displayed.
29,156,839
1
29,172,240
On the <URL> is listed as an example of using the dc.js library. He was able to color code the rows, as shown in the image below, which I'm trying to mimic. <IMAGE> See here for my code: <URL> In particular, how would I change the color of the rows so that all rows with the name 'Red' are red, with the name 'Blue' are Blue, and the name 'White' are white. Javascript: ''' items = [ {Id: "01", Name: "Red", Price: "1.00", Quantity: "1",TimeStamp:111}, {Id: "02", Name: "White", Price: "10.00", Quantity: "1",TimeStamp:222}, {Id: "04", Name: "Blue", Price: "9.50", Quantity: "10",TimeStamp:434}, {Id: "03", Name: "Red", Price: "9.00", Quantity: "2",TimeStamp:545}, {Id: "06", Name: "White", Price: "100.00", Quantity: "2",TimeStamp:676}, {Id: "05",Name: "Blue", Price: "1.20", Quantity: "2",TimeStamp:777} ]; var ndx = crossfilter(items); var Dim = ndx.dimension(function (d) {return d.Name;}) dc.dataTable("#Table") .width(250).height(800) .dimension(Dim) .group(function(d) {return ' '}) .size(100) // number of rows to return .columns([ function(d) { return d.Id;}, function(d) { return d.Name;}, function(d) { return d.Price;}, function(d) { return d.Quantity;}, function(d) { return d.TimeStamp;}, ]) .sortBy(function(d){ return d.Price;}) .order(d3.ascending); dc.renderAll(); ''' HTML: ''' <table class='table table-hover' id='Table'> <thead> <tr class='header'> <th>ID</th> <th>Name</th> <th>Price</th> <th>Quantity</th> <th>Timestamp</th> </tr> </thead> </table> ''' How could this be done considering the only attributes that <URL> has are size, columns, sortBy, and order?
You had a syntax error and an unknown symbol in your codepen there. The idea is to use 'chart.selectAll' to grab the rows, and then color them based on the data somehow: ''' .renderlet(function(chart){ chart.selectAll('tr.dc-table-row') .style('background-color', function(d) { return d ? d.Name : null; }) }); ''' <URL> Here's my fork: <URL>
22,708,042
1
22,708,178
I want to display an action which hold an introduction and message from manager for few seconds then go to home action any idea how to achieve that something like the following image <IMAGE>
Simple way of achieving this is using the meta refresh tag. Just put the following code into the head of your index.html: ''' <meta http-equiv="refresh" content="5; url=home.html"> ''' Where '5' represents the seconds when the refresh occurs and 'url=home.html' is the path where the refresh will redirect. So in your you put introduction content and in you build your website. Hope this helps.
14,644,711
1
14,654,708
I dont know where i am going wrong . I need to upload APK to google play and whenever i am trying to upload it , it is showing an error message as displayed in the attached screenshot. The error is that " You need to add an icon to your APK " but for sure i have already added an icon to my APk in my manifest file . I dont what it is asking for whether it is error because of icon resolution or there is something i am lacking with . pls help .<IMAGE>
It is likely that in your manifest that you do not have an icon defined or are referencing an image that does not exist.
9,139,386
1
10,139,720
Which will scale best for performance, file-size, (and my sanity): Animated '.gif's or a spritesheet with animations using CSS (and JS when need be)? ### Filesize So, I'm honestly not sure which will be better here since I don't understand the compression of frames in '.gif'. My guess would be that they would end up about equal if I can swing it right, but if this is wrong, or if this is a factor for a different reason let me know. The main advantage here, in my mind, goes to Spritesheets as I would be able to include multiple animations on a single sheet (and we're talking hundreds of animated sprites here). And based on <URL>'. Where as with a '.gif' file I really can only include one animation since each will likely have a different duration. Also, some of the animations repeat for a given sprite, so the spritesheet would only have to have one copy of the frames, where as a '.gif' would need to have all the frames (at least to my knowledge). ### Performance Guessing here again, my intuition tells me that animated '.gif's are going to be significantly faster as I won't have to manage all the animations at the same time I'm doing a lot of JS code for other things. But, I don't know for sure, maybe browsers take a significant hit with 30+ animated '.gif's. ### My Sanity The spritesheets are made for me, so my work would be high in the beginning (writing and animation engine and hand coding one/each sheet). But once written, it is usable for good and a change in a spritesheet requires minimal changes to code. On the other hand, animated '.gif' files are not a cake to make in Photoshop (if you have a better program, let me know). And each one must be hand made and is a long process. But, once they are made, I don't really have to change them. My spritesheets aren't likely to change very quickly, so chances are it will be a one and done. ### My Question (tl;dr) Which is going to scale better to the hundreds of animations in terms of filesize (including HTTP header transfer as it will go over the web), performance in modern browsers, and ease of creation (lowest priority, but if you can make my job easier, or argue to this, I would be grateful), Animated '.gif' files built from spritesheets, or simply using CSS and the spritesheets I already have? ### Examples <IMAGE>
As I was curious, I implemented it in javascript. <URL>. What I found out: - - - - <URL> More info in the JsFiddle demo page.
5,113,901
1
5,121,105
I am trying to write program that displays a window with simulated "tv static". I have it mostly working but when I expand the window grid lines form. I have no idea what could be causing this as this is my first OpenGL (glut) program. Any suggestions? thanks in advance<IMAGE> ''' #include <GLUT/glut.h> #include <stdlib.h> #include <time.h> using namespace std; void display(void){ /* clear window */ glClear(GL_COLOR_BUFFER_BIT); int maxy = glutGet(GLUT_WINDOW_HEIGHT); int maxx = glutGet(GLUT_WINDOW_WIDTH); glBegin(GL_POINTS); for (int y = 0; y <= maxy; ++y) { for (int x = 0; x <= maxx; ++x) { glColor3d(rand() / (float) RAND_MAX,rand() / (float) RAND_MAX,rand() / (float) RAND_MAX); glVertex2i(x, y); } } glEnd(); /* flush GL buffers */ glFlush(); } void init(){ /* set clear color to black */ glClearColor (0.0, 0.0, 0.0, 1.0); /* set fill color to white */ glColor3f(1.0, 1.0, 1.0); /* set up standard orthogonal view with clipping */ /* box as cube of side 2 centered at origin */ /* This is default view and these statement could be removed */ glMatrixMode (GL_PROJECTION); glLoadIdentity (); glOrtho(0, glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT), 0, 0, 1); glDisable(GL_DEPTH_TEST); glMatrixMode (GL_MODELVIEW); glLoadIdentity (); } int main(int argc, char** argv){ srand(time(NULL)); /* Initialize mode and open a window in upper left corner of screen */ /* Window title is name of program (arg[0]) */ glutInit(&argc,argv); //You can try the following to set the size and position of the window glutInitWindowSize(500,500); glutInitWindowPosition(0,0); glutCreateWindow("simple"); glutDisplayFunc(display); init(); glutIdleFunc(display); glutMainLoop(); } ''' Edit: I can remove the lines by using 'glRecti'; however the pixels get bigger the larger the window gets.
Your screen is 'width*height' size, but you are actually drawing '(width+1)*(height+1)' points. Also, your boundary pixels are drawn right on the boundary lines, so I'm not sure they'll be visible. Solution: ''' for (int y = 0; y < maxy; ++y) { for (int x = 0; x < maxx; ++x) { glColor3d(rand() / (float) RAND_MAX,rand() / (float) RAND_MAX,rand() / (float) RAND_MAX); glVertex2f(x+0.5f, y+0.5f); } } ''' Notice the change in loop conditions and type of glVertex call.
21,719,243
1
21,720,263
Per the <URL>, I figure that I should be able to create the following links, and have them properly open a Web Intents window to twitter. The Web Intents window opens properly, however I get the error "Sorry, that page doesn't exist". Here is what I have done. I added the following script tag to my Angular template: ''' <script type="text/javascript" src="//platform.twitter.com/widgets.js"></script> ''' Then, I have an ng-repeat for each tweet, which contains the following code: ''' <p><a ng-href="http://twitter.com/intent/tweet?in_reply_to={{ tweet.id }}">Reply</a></p> <p><a ng-href="http://twitter.com/intent/retweet?tweet_id={{ tweet.id }}">Retweet</a></p> <p><a ng-href="http://twitter.com/intent/favorite?tweet_id={{ tweet.id }}">Favorite</a></p> ''' For each tweet that is on the page, the proper HTML is generated. In the case that the tweet has the id 431111460186759200, the following html is generated for these links: ''' <p><a ng-href="http://twitter.com/intent/tweet?in_reply_to=431111460186759200" href="http://twitter.com/intent/tweet?in_reply_to=431111460186759200">Reply</a></p> <p><a ng-href="http://twitter.com/intent/retweet?tweet_id=431111460186759200" href="http://twitter.com/intent/retweet?tweet_id=431111460186759200">Retweet</a></p> <p><a ng-href="http://twitter.com/intent/favorite?tweet_id=431111460186759200" href="http://twitter.com/intent/favorite?tweet_id=431111460186759200">Favorite</a></p> ''' When I click on these links, the proper modal is opened, in the recommended size (thanks to the widget.js file I embedded), with the correct URL. However, instead of showing the Web Intent screen, it shows me the following: <IMAGE> Does anyone here have enough experience with Twitter and their Web Intents to help me?
It's simply because there is no tweet with id 431111460186759200. If you try with the id 431216327143858177 it works fine: <URL>. If the tweet your code is referencing still exists, try using tweet.id_str instead of tweet.id. For example Javascript can't handle numbers as big as tweet ids so for example 431216327143858177 becomes 431216327143858200. Using id_str you would be sure it works in any language. And by the way it's better to use https links rather than http ones.
13,723,747
1
13,723,833
I'm looking for the best way to implement alternating row colours for a theoretically infinite number of nested levels. Below is an example of the markup i'm testing with and the jsFiddle <URL> With nth-child it's very difficult to get the alternating colours to work correctly, you need to effectively hardcode the combinations for each level and the css rules grow exponentially. I can achieve the result I want using javascript, however the lists are completely dynamic and things are added and removed constantly. Performance wise using javascript doesn't seem like an option and could have some pretty massive implications. This only needs to work in IE9+ <IMAGE> ''' <ul> <li> <span>Item</span> </li> <li> <span>Item</span> </li> <li> <span>Item</span> <ul> <li> <span>Item</span> <ul> <li><span>Item</span></li> <li><span>Item</span></li> <li><span>Item</span></li> <li><span>Item</span></li> <li><span>Item</span></li> </ul> </li> <li> <span>Item</span> <ul> <li><span>Item</span></li> <li><span>Item</span></li> <li><span>Item</span></li> <li><span>Item</span></li> <li><span>Item</span></li> </ul> </li> <li> <span>Item</span> <ul> <li><span>Item</span></li> <li><span>Item</span></li> <li><span>Item</span></li> <li><span>Item</span></li> <li><span>Item</span></li> </ul> </li> </ul> </li> </ul> '''
Such implementation is not possible via css only. You will have to use javascript. Also, usage of JS shouldn't cause such horrible performance. Just have JS check and update whenever new values are added or removed. Then, we're talking about a performance of linearly dependent on number of rows. Hardly different from the browser trying to figure it out from css rules if it were possible (also linearly dependent on number of rows or worse).
30,390,384
1
30,390,457
I use a scrolling navigation so as the navigation is folowing the user and no need to go to the top to change the page. Because the page is an app page, on the very very top of it i want to add something like this : <IMAGE> My problem is that the scrolling navigation has a really hardcoded css structure, and my question is if there is a javascript/jQuery way to just put that new div block at the top of everything. Thank you
you can simply try: ''' #new-div-id { position:fixed; top:0px; left: 0px; z-index: 999; } '''
6,614,478
1
6,684,785
This question relates to the Appcelerator Titanium platform, not the stock iOS SDK. I'm making a tag cloud with a 'layout: horizontal' view. I'm most of the way there, but I can't get the final 'Titanium.UI.Label' on a line to wrap if it doesn't fit. Instead, it gets ellipsized (in a useless manner). <IMAGE> Is there a way I can prevent this on iOS? Seems to work fine on Android.
If you try to set the label width to auto, Titanium will calculate the label width in runtime. It make sense to get a ellipsized label in horizontal view. You may need to determine the dynamic label width in your tag cloud case. But just leave it to titanium, you just need to change the dynamic width to static width with this tricky code. ''' for (var i = 0; i < data.length; i++) { var label = Ti.UI.createLabel({ text: data[i], width: 'auto', height: 20,left: 5, top: 5}); label.width = label.width + 5; //this determine width in runtime assign back to static width view.add(label); } '''
28,027,946
1
28,028,073
I'm trying to debug a qunit ember integration test on Webstorm. Qunit is the same framework that ember is tested with. Our test is similar to this: ''' import startApp from '../helpers/start-app'; var App; module('Integration Tests', { setup: function() { App = startApp(); }, teardown: function() { Ember.run(App, 'destroy'); }); test("Checking hub page",function(){ expect(2); visit('/hub'); andThen(function(){ console.log(currentRouteName()); ok('in to the function'); }); }); ''' I am trying these settings: <IMAGE> Edit------------------------------ I updated my run config but the application exits with the following error: ''' debugger listening on port 59771 version: 0.1.7 Could not find watchman, falling back to NodeWatcher for file system events BuildingBuilding.Building..Building...Building... Build successful - 1853ms. c[?25l[8;NaNrtty.setRawMode: Use 'process.stdin.setRawMode()' instead. tty.js:37 throw new Error('can't set raw mode on non-tty'); ^ '''
You should have used ember to run your code. And you are running it as a simple node.js application ('node foo-test.js'). Moreover, Node won't accept EcmaScript 6 syntax unless being run with --harmony switch. Please make sure to update your run configuration accordingly (to run ember and pass your spec as a parameter to it)
20,251,012
1
20,254,279
I can't get my relativelayout to be able to be set to transparent. I have tried many different methods, custom view from class, adding android:background="@android:color/transparent" etc. They either show a white like in the picture below, or they show a solid color of whatever the hex is? <IMAGE> Even programmatically using '.setBackgroundColor(Color.TRANSPARENT);' results in the above picture.
Figured it out. The main LinearLayout of my view was the layout making it have a white background. I added my view under my listview in a RelativeLayout and it works great. Thanks all!
20,422,492
1
20,426,877
I am trying to debug a simple C program using TCF. It basically works, but the problem is, that I only see the disassembly but without any debug informatione - so just the machine code. This is how gcc (using MinGW) is called: ''' gcc -O0 -g3 -Wall -c -fmessage-length=0 -o main.o "..\main.c" gcc -o debugme.exe main.o ''' Whereas ths is the TCF Trace: ''' 360.192 Inp: E Breakpoints status "file:/C:/Users/falkstef/runtime-EclipseApplication/test/main.c:3703" {Instances:[{LocationContext:"P7092",Error:"Unresolved source line information"}]} 360.192 Inp: E Breakpoints status "file:/C:/Users/falkstef/runtime-EclipseApplication/test/main.c:3697" {Instances:[{LocationContext:"P7092",Error:"Unresolved source line information"}]} 360.192 Inp: E Breakpoints status "file:/C:/Users/falkstef/runtime-EclipseApplication/test/main.c:3701" {Instances:[{LocationContext:"P7092",Error:"Unresolved source line information"}]} 360.192 Inp: E Breakpoints status "file:/C:/Users/falkstef/runtime-EclipseApplication/debugme/main.c:3717" {Instances:[{LocationContext:"P7092",Error:"Unresolved source line information"}]} ... 360.468 Out: C 1778 Symbols findByAddr "P7092" <PHONE> 360.468 Inp: R 1778 {Format:"Symbol not found",Time:1386328360468,Code:22} null 360.469 Out: C 1779 Symbols findByAddr "P7092" <PHONE> 360.469 Inp: R 1779 {Format:"Symbol not found",Time:1386328360469,Code:22} null 360.469 Out: C 1780 Symbols findByAddr "P7092" <PHONE> 360.469 Inp: R 1780 {Format:"Symbol not found",Time:1386328360469,Code:22} null 360.469 Out: C 1781 Symbols findByAddr "P7092" <PHONE> ... ''' Can anyone help me here? Running services according to the Locator Hello Message: ''' ["ZeroCopy","Diagnostics","Profiler","Disassembly","DPrintf", "Terminals","PathMap","Streams","Expressions","SysMonitor", "FileSystem","ProcessesV1","Processes","LineNumbers", "Symbols","StackTrace","Registers","MemoryMap","Memory", "Breakpoints","RunControl","ContextQuery","Locator"] ''' ''' // .. somewhere in linenumberswin32.c if (!SymGetLineFromName(get_context_handle(ctx), NULL, file, line, &offset, &img_line)) { DWORD win_err = GetLastError(); if (win_err != ERROR_NOT_FOUND) { err = set_win32_errno(win_err); } } // ... ''' See <URL>. ''' // this returns false: BOOL SymGetLineFromName(HANDLE hProcess, PCSTR ModuleName, PCSTR FileName, DWORD dwLineNumber, PLONG plDisplacement, PIMAGEHLP_LINE Line) { typedef BOOL (FAR WINAPI * ProcType)(HANDLE, PCSTR, PCSTR, DWORD, PLONG, PIMAGEHLP_LINE); static ProcType proc = NULL; if (proc == NULL) { proc = (ProcType)GetProc("SymGetLineFromName"); if (proc == NULL) return 0; } return proc(hProcess, ModuleName, FileName, dwLineNumber, plDisplacement, Line); } ''' Screenshot (<URL> <IMAGE>
Stefan, you won't be able to debug this file using the current implementation of TCF because the file you generated using MinGW is in the PE file format but the debug information are in DWARF. As far as I know this is not supported by TCF right now, only by GDB. See <URL>. I suggest you build a new .exe file using Visual Studio which will generate a PE file with MS debug format or that you switch to Linux (ELF + DWARF)
30,237,035
1
30,242,111
I am to design a report which will be having given rows, I have tried with and , but I am facing issue with grouping. Is there any other control or any custom control or any way of customizing Table which I can use to design the following formatted rows in report. Any link with demo, sample or POC would be great help. <IMAGE>
Kind hard to tell what you're going for from your picture/description, but I'm guessing you may want to use a List object. You can put your group at the list object level, and then add text boxes, tables, images or whatever you need inside the list. You'll get a set of whatever is inside the list for each group, using the data from that group. Take a look at the sample/description here, which looks similar to what you're trying to do: <URL>
16,056,778
1
16,192,164
I am working on integrating Twitter in an app and while all works as it should I am stumped on the 'setOnItemClickListener()' not triggering when a 'ListView' 'item' has a link in it. It works just fine when an 'item' does not have a link (URL) in it. Clicking on the URL itself opens the web page in a Browser. Please see the screenshots added as reference at the end of the post. It is a custom 'ListView' that employs a 'BaseAdapter'. I am not sure which piece of code to put in but on being pointed to a code block that the folks here may need, I will add it immediately. The idea behind needing to ignore the links (URLs) in an item is to provide a functionality that shows the tweet details when a user clicks on one. Something similar to what the Twitter Android app does. So what do I do to make the 'setOnItemClickListener()' ignore the links in items? Okay. SO I am not sure if it is relevant to the question, but, from a combination of a few solutions from SO which led me to the <URL> Open Source project, I have managed to get a few things working. But unfortunately, it doesn't address my primary question. How do I make the 'setOnItemClickListener()' ignore the links in an item so I can click it and show the details in another Activity and yet, when I click on a link, not trigger the 'setOnItemClickListener()'? I keep getting partial solutions in every attempt I make. But at times, when I click on a 'link', the 'setOnItemClickListener()' triggers too. This is how it the flow looks at the moment: <IMAGE> In the top two screenshots, it works as it should. Not clicking on a link after all. In the bottom two, however, when I click on the link, it shows the Profile for the user (). This part is derived from the TweetLanes source. The problem is, the click listener is also triggered. This is one of the solutions I am trying out. In this case, I have commented out the 'setOnItemClickListener()' and am using a 'OnClickListener()' on the 'TextView'. This is the one method which has partial success so far.
You probably want to take a look at <URL> He presents a TextView that issues this problem basically by introducing a different 'LinkMovementMethod': ''' public static class LocalLinkMovementMethod extends LinkMovementMethod{ static LocalLinkMovementMethod sInstance; public static LocalLinkMovementMethod getInstance() { if (sInstance == null) sInstance = new LocalLinkMovementMethod(); return sInstance; } @Override public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) { int x = (int) event.getX(); int y = (int) event.getY(); x -= widget.getTotalPaddingLeft(); y -= widget.getTotalPaddingTop(); x += widget.getScrollX(); y += widget.getScrollY(); Layout layout = widget.getLayout(); int line = layout.getLineForVertical(y); int off = layout.getOffsetForHorizontal(line, x); ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class); if (link.length != 0) { if (action == MotionEvent.ACTION_UP) { link[0].onClick(widget); } else if (action == MotionEvent.ACTION_DOWN) { Selection.setSelection(buffer, buffer.getSpanStart(link[0]), buffer.getSpanEnd(link[0])); } if (widget instanceof TextViewFixTouchConsume){ ((TextViewFixTouchConsume) widget).linkHit = true; } return true; } else { Selection.removeSelection(buffer); Touch.onTouchEvent(widget, buffer, event); return false; } } return Touch.onTouchEvent(widget, buffer, event); } } ''' --- Based on it, I advice you to fix the file 'TwitterLinkify.java' (the function that sets the link movement) like this: ''' private static final void addLinkMovementMethod(TextView t) { MovementMethod m = t.getMovementMethod(); if ((m == null) || !(m instanceof LocalLinkMovementMethod)) { if (t.getLinksClickable()) { t.setMovementMethod(LocalLinkMovementMethod.getInstance()); } } } ''' Thanks
6,867,002
1
6,872,461
I'm developing site which provides allow to display external sites into iframe with extra information, similar to google images. <IMAGE> In most cases this works well, but some sites uses javascripts calls which access to parent frame, that causes "Unsafe JavaScript attempt to access frame with URL" and other errors and these sites doesn't displayed correctly. Are there any way to fix it at least for some sites? Some kind of sandboxing? Or allowing child frame to access parent? Replace window.top somehow?
You will probably have to make proxy. ''' <?php $content = file_get_contents("http://addr.to/your/content.html"); $content = preg_replace("~window\.top.*?~i", "", $content); echo $content; ''' but it will be VERY unstable this way!
21,650,422
1
21,651,720
I am retrieving a iCal from a Google Calendar '"Private adress"' link in JSON format. <IMAGE> I can see both events that are 'available' and 'busy' but can not see any difference between them. I imported them to PHP, also tried the '?alt=json' option to get a JSON object but no where saw a distinction between both. But if I look at the same calendar shared with me with the 'free/busy information (Hide details)' option checked, then I only see the busy events. Is there a way to distinguish them in the iCal so I can import them into my PHP functions and not mix events that exist but are marked as available with events marked as busy ?
There should be a difference in the value for 'TRANSP'. <URL>
26,270,199
1
26,270,398
This might be a stupid question, but I tried finding an answer and did not find anything. Are negative numbers considered as 'nothing'(null) in vb.net? Debug mode: <IMAGE> Above is a query to db to find me all values where the district is 'value'. Its a list in razor view and Since I did not want anything to be displayed by default, I set the district ID to -1 and since there is nothing of that value in the database, it should return anything. However, it still returns me the value where district is NULL. How is that?
Negative values are not null. However, you are using 'Or' instead of 'OrElse' (<URL> Or causes both sides of the statement to be called, and it does not short-circuit. Also, you should call the null check before the value check. If you don't short-circuit with the null check, you'll end up calling a comparison of a null value ('m.DistrictId') against a non-null value ('districtId').
18,909,540
1
18,910,180
I am implementing paging in my datalist. (visual studio 2008) For that i have datatable on which i want to make query for paging. I have following datatable: <IMAGE> I wanted to implement following SQLquery: ''' select top 5 * from (select ROW_NUMBER() OVER (ORDER BY Index) as Row from users) T where Row > " 10 ''' I want to make same query on this datatable as above. I was confused how to use "top" to query datatable. For that i made following attempt: ''' DTResult.Select("Index < " & Integer.Parse(ddlPage.SelectedValue.ToString())) ''' (note: 'ddlPage' is my dropdown containing numbers for paging like 5,10,25,etc) This attempt is not giving me intended result. please help me.
You have to use Linq to get SQL like operations in C# ''' DataTable MyTable = new DataTable();// Yur Table here var FirstResult = from Row in MyTable.AsEnumerable() orderby Row.Field<int>("Index") select new { KioskId = Row.Field<string>("KioskId"), Index = Row.Field<int>("Index"), FileName = Row.Field<string>("FileName") }; var AfterRowNumbering = FirstResult.Select((x, index) => new { KioskId=x.KioskId, Index=x.Index, FileName = x.FileName, Row_Number = index }).Take(5); var FinalResult = from row in AfterRowNumbering where row.Row_Number > 10 select row; ''' This expressions can be further simplified.
19,060,378
1
19,236,295
How to remove one specific selected file from input file control? I have an input file control with the option to select multiple files; however, I want to validate a file and if it has an wrong extension then I should remove that file from the file control itself, is it possible? I tried as below ''' <input type="file" name="fileToUpload" id="fileToUpload" multiple/> <script> $("#fileToUpload")[0].files[0] </script> ''' Below is the screenshot of the object but I am not able to modify it <IMAGE>
As other people pointed out, <URL> API. Below is a round about way of completely avoiding needing to modify the 'FileList'. Steps: 1. Add normal file input change event listener 2. Loop through each file from change event, filter for desired validation 3. Push valid files into separate array 4. Use FileReader API to read files locally 5. Submit valid, processed files to server Event handler and basic file loop code: ''' var validatedFiles = []; $("#fileToUpload").on("change", function (event) { var files = event.originalEvent.target.files; files.forEach(function (file) { if (file.name.matches(/something.txt/)) { validatedFiles.push(file); // Simplest case } else { /* do something else */ } }); }); ''' Below is a more complicated version of the file loop that shows how you can use the 'FileReader' API to load the file into the browser and optionally submit it to a server as a Base64 encoded blob. ''' files.forEach(function (file) { if (file.name.matches(/something.txt/)) { // You could also do more complicated validation after processing the file client side var reader = new FileReader(); // Setup listener reader.onload = (function (processedFile) { return function (e) { var fileData = { name : processedFile.name, fileData : e.target.result }; // Submit individual file to server $.post("/your/url/here", fileData); // or add to list to submit as group later validatedFiles.push(fileData); }; })(file); // Process file reader.readAsDataURL(file); } else { /* still do something else */ } }); ''' A note of caution about using 'FileReader' API. Base64 encoding a file will increase its size by around 30%. If that isn't acceptable you will need to try something else.
16,821,197
1
16,821,430
I'm trying to get Matlab to take this as a function of 'x_1' through 'x_n' and 'y_1' through 'y_n', where 'k_i' and 'r_i' are all constants. <IMAGE> So far my idea was to take 'n' from the user and make two 1xn vectors called 'x' and 'y', and for the 'x_i' just pull out 'x(i)'. But I don't know how to make an arbitrary sum in MATLAB. I also need to get the gradient of this function, which I don't know how to do either. I was thinking maybe I could make a loop and add that to the function each time, but MATLAB doesn't like that.
I don't believe a loop is necessary for this calculation. MATLAB excels at vectorized operations, so would something like this work for you? ''' l = 10; % how large these vectors are k = rand(l,1); % random junk values to work with r = rand(l,1); x = rand(l,1); y = rand(l,1); vals = k(1:end-1) .* (sqrt(diff(x).^2 + diff(y).^2) - r(1:end-1)).^2; sum(vals) ''' EDIT: Thanks to @Amro for correcting the formula and simplifying it with 'diff'.
16,589,017
1
19,941,503
I pinned 'Notepad2-mod' to the taskbar. When I click the pinned shortcut, it opens a new instance but doesn't stack in place. It begins a new stack. Additional clicks will utilize the second stack. This can probably best be explained via screenshot: <IMAGE> The oddest part is it used to stack on the taskbar shortcut if I started it by clicking on it or using WIN+num, but if I started 'Notepad2-mod' by right-clicking on a file and using "open with notepad2-mod" it would stack in a new stack. Now, they all stack in a new stack (not on the taskbar-pinned shortcut). Both the "open with notepad2-mod" registry shortcut and the taskbar-pinned shortcut run the same executable. Ultimately, I'd like them all to stack in the same place, on top of the taskbar-pinned icon. ''' 1) What did I do to persuade it to behave like this? 2) How can I convince it to all stack on the pinned icon? ''' --- I just noticed in the Task Manager that when I double click a .txt file I'm running a version of this binary named 'Notepad2.exe' and when I click on the icon on the Taskbar I'm running a copy of this same binary named 'notepad.exe'. I must have done that to fool Windows 7 into thinking it was using vanilla Notepad. I thought changing this might fix it, but it did not. They still stack on a different portion of the Taskbar. They even respond to keyboard shortcuts like 'Start Button+Number' for the slot where they do actually stack.
Thanks to the <URL>, this issue is fixed. Go read his site for a better answer than mine, but, in case his site ever goes away, here are the relevant snippets: > Notepad2 windows are now assigned to a custom 'AppUserModelID', that's why multiple icons may appear if Notepad2.exe is directly pinned to the taskbar. To fix this, open a window first, and then pin it to the taskbar from the Notepad2 taskbar button context menu. Note that if you have followed the rest of his instructions on the <URL> and set it up to redirect 'notepad.exe' to 'notepad2.exe', you actually have to start up 'Notepad2.exe' directly, then right click on the taskbar instance and click "Pin to Taskbar". Now that I did that, all my Notepad2 instances stack in the same place on the taskbar! Note that the author of Notepad2 says that you have to add code in your application to handle this. <URL>.