text
stringlengths
70
452k
dataset
stringclasses
2 values
Unity How to remove the elements label (Element 0 - Element ...) in a array in the inspector In my editor for one of my scripts I am trying to figure out how to remove what is in the red box (Element 0 - Element 14) so basically you would just see the string inputs. My Editor Script so far : [CustomEditor(typeof(Change))] public class Change_Editor : Editor { public override void OnInspectorGUI(){ // Grab the script. Change myTarget = target as Change; // Set the indentLevel to 0 as default (no indent). EditorGUI.indentLevel = 0; // Update serializedObject.Update(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginVertical(); EditorGUILayout.PropertyField(serializedObject.FindProperty("SceneNames"), true); EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); // Apply. serializedObject.ApplyModifiedProperties(); } } EDIT : MotoSV's answer worked and the result is shown below. To show just the value of each array index you simply have to enumerate through the array and display a field just for the value: [CustomEditor(typeof(Change))] public class Change_Editor : Editor { public override void OnInspectorGUI() { // Grab the script. Change myTarget = target as Change; // Set the indentLevel to 0 as default (no indent). EditorGUI.indentLevel = 0; // Update serializedObject.Update(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginVertical(); // >>> THIS PART RENDERS THE ARRAY SerializedProperty sceneNames = this.serializedObject.FindProperty("SceneNames"); EditorGUILayout.PropertyField(sceneNames.FindPropertyRelative("Array.size")); for(int i = 0; i < sceneNames.arraySize; i++) { EditorGUILayout.PropertyField(sceneNames.GetArrayElementAtIndex(i), GUIContent.none); } // >>> EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); // Apply. serializedObject.ApplyModifiedProperties(); } } I have not fully tested this, i.e. saved a scene, loaded up and verified all fields are serialized, but the look in the inspector seems to match what you're after. Thank you very much for this and it works as intended. Ill post a screenshot in-case anyone else needs to see.
common-pile/stackexchange_filtered
Double replacement for site collection replacement token in master page? I am setting up custom branding for a site, using a custom master page, and linking to custom css, image and script files all hosted in the Style Library on the root web of the site collection. As suggested in this answer, I am using the replacement token ../.. to refer to the site collection. So, for example, some of my links look like this: <link href="../../Style Library/custom/css/custom_v2.css" rel="stylesheet" type="text/css"/> <asp:Image ImageUrl="../../Style Library/custom/img/logo3.png" runat="server" /> This works fine for the home page of the site, and for any main list view for any of the lists or libraries on the site. However, if I go to a "system" page, like Site Contents or Site Settings, everything gets broken, and I can see that my links have turned into this: <link href="../../sites/mysite/Style Library/custom/css/custom_v2.css" rel="stylesheet" type="text/css"/> <asp:Image ImageUrl="../../sites/mysite/Style Library/custom/img/logo3.png" runat="server" /> So it seems as though the URL replacement is happening twice in those cases. Why is this happening, and is there anything I can do about it? (The same custom master page is specified for both SPWeb.MasterUrl and SPWeb.CustomMasterUrl.) Is your site publishing enabled? Then you can use SPUrl token instead of .. Yes it is, and I just found this other answer over on SO: http://stackoverflow.com/a/3898034/988264 , which I am trying out right now. Ok, I'm marking Amal's answer as the correct one, since it did lead me to solving the problem. However, I wanted to add an answer of my own with a little more detail about the URL tokens, and how to use them. I had previously run across this MSDN page on URLs and Tokens in SharePoint 2013. In it, I saw that there is a token ~sitecollection that can be used at the beginning of a URL, so I tried this: <link href="~sitecollection/Style Library/custom/css/custom_v2.css" rel="stylesheet" type="text/css"/> <asp:Image ImageUrl="~sitecollection/Style Library/custom/img/logo3.png" runat="server" /> That didn't work. Some kind of URL replacement was happening, but it was definitely not what I expected, and it was an invalid URL so the resources weren't getting loaded. What they don't tell you on that page is the correct syntax for using the token, and that is this: <% $SPUrl:~sitecollection/Path/To/Resource %> Once I learned that was how to actually use the tokens, I implemented this: <link href="<% $SPUrl: ~sitecollection/Style Library/custom/css/custom_v2.css%>" rel='stylesheet' type='text/css'/> <asp:Image ImageUrl='<% $SPUrl:~sitecollection/Style Library/custom/img/logo3.png %>' runat="server" /> Which is working great. Interestingly, for script links, you have to wrap the token in an ASP literal control, so a script link using this method looks like this: <script src='<asp:Literal runat="server" Text="<% $SPUrl:~sitecollection/Style Library/custom/js/libs/jquery-2.1.1.min.js %>" />' type='text/javascript'></script> So, I hope that helps anyone trying to figure out how to use the URL replacement tokens. Dylan Cristy: You can mark yours as the answer :) For CSS you can use <SharePoint:CssRegistration name="<% $SPUrl:-sitecollection/Style Library/custom/css/custom_v2.css" %>" runat="server"/> For Site Logo you can use <SharePoint:SiteLogoImage LogoImageUrl="/Style Library/AdventureWorks/logo.png" AlternateText="Back to Home" ToolTip="Back to Home" runat="server"/> Check this http://msdn.microsoft.com/en-us/library/office/gg430141(v=office.14).aspx from more on branding
common-pile/stackexchange_filtered
C child window procedure In C language, this is a child button window that I have put inside a window made with CreateWindowEx(). I am wondering if there's a way give this button window and ID so I can callback a procedure and make the button interactive for user experience. Maybe implement it inside WM_COMMAND -> switch(LOWORD(wParam)){ case: THEIDOF_BUTTON} This code runs under LRESULT CALLBACK window procedure of parent windows as you can see with WM_CREATE HWND buttonBox; case WM_CREATE: (HWND)buttonBox = CreateWindow(WC_BUTTON, TEXT("ABUTTON"), WS_CHILD | WS_VISIBLE | WS_SIZEBOX, 500, 400, 300, 300, parentWindow, NULL, hInstance, NULL); read about hMenu parameter in CreateWindowEx A handle to a menu, or specifies a child-window identifier, depending on the window style .. For a child window, hMenu specifies the child-window identifier, an integer value used by a dialog box control to notify its parent about events. and from GetDlgCtrlID function documentation: An application sets the identifier for a child window when it creates the window by assigning the identifier value to the hmenu parameter when calling the CreateWindow or CreateWindowEx function. so you need next code for create child: buttonBox = CreateWindow(WC_BUTTON, TEXT("ABUTTON"), WS_CHILD | WS_VISIBLE | WS_SIZEBOX, 500, 400, 300, 300, parentWindow, (HMENU)ID_BUTTON_BOX, hInstance, NULL); where ID_BUTTON_BOX some integer value. and you get in back in WM_COMMAND as wParam (low word) or in WM_NOTIFY here exist thin point - the CreateWindow[Ex] accept the LONG_PTR in place hMenu as child-window identifier. so 64-bit value on x64 system. the same result will be if call SetWindowLongPtr with GWLP_ID. we can call GetWindowLongPtr(buttonBox, GWLP_ID) after create and check that it return exactly ID_BUTTON_BOX. but if use GetDlgCtrlID function - it return (int)ID_BUTTON_BOX - truncated to 32-bit id. in case WM_NOTIFY despite idFrom from NMHDR structure declared as UINT_PTR here really only truncated to 32-bit id because the GetDlgCtrlID used for initialize it. the WM_COMMAND at all truncate id to low 16 bit in wParam. so for example if we define ID_BUTTON_BOX as 0x9012345678 when calling the CreateWindow or CreateWindowEx function - we got back exactly 0x9012345678 if call GetWindowLongPtr(buttonBox, GWLP_ID). but GetDlgCtrlID(buttonBox) return already 0x12345678 only. also the 0x12345678 will be in wParam and idFrom when we handle WM_NOTIFY and on WM_COMMAND we got only 0x5678 as control id. so despite we can set full 64 bit value for child window identifier (say pointer to some structure casted to ULONG_PTR) and get it back as is in call GetWindowLongPtr(buttonBox, GWLP_ID) - in WM_NOTIFY and WM_COMMAND we got back only low 32 or 16 bit of identifier. because this usually used only 16 bit values for child id I was looking for SetWindowLongPtr() function, found it. thanks sir! I see, it's still interesting it uses HMENU as the variable type, but yes you're right it's a lot easier, i'll test it now Once you have the HWND for your button, you must call SetWindowLongPtr to set the button ID: HWND buttonBox; #define ID_BUTTON_BOX (100) // or whatever you like, should be unique for the parent window. //.. case WM_CREATE: buttonBox = CreateWindow(WC_BUTTON, TEXT("ABUTTON"), WS_CHILD | WS_VISIBLE | WS_SIZEBOX, 500, 400, 300, 300, parentWindow, NULL, hInstance, NULL); SetWindowLongPtr(buttonBox, GWL_ID, (LONG_PTR)ID_BUTTON_BOX); Here's a link to the MSDN doc: https://msdn.microsoft.com/en-us/library/windows/desktop/ms644898(v=vs.85).aspx While possible, this is certainly not the standard procedure to assign an ID to a control. More commonly, the control ID is passed into the call to CreateWindow[Ex], or statically assigned in a resource script. SetWindowLongPtr is really only useful, in case you need to change the control ID (which is rare in itself).
common-pile/stackexchange_filtered
Need help modifying HLSL shader I am trying to modify this shader code which adds a phosphor effect in the form of "phosphor trails" much like an old CRT monitor. This code is part of MAME emulation software package. Can anyone help me make a change to this so that the phosphor trail pixels are 50% less bright? I am new to hlsl and tried a few things to change the color parameters but I couldn't get it to work. Original code: // license:BSD-3-Clause // copyright-holders:Ryan Holtz //----------------------------------------------------------------------------- // Phosphor Effect //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Sampler Definitions //----------------------------------------------------------------------------- texture Diffuse; sampler DiffuseSampler = sampler_state { Texture = <Diffuse>; MipFilter = LINEAR; MinFilter = LINEAR; MagFilter = LINEAR; AddressU = CLAMP; AddressV = CLAMP; AddressW = CLAMP; }; texture LastPass; sampler PreviousSampler = sampler_state { Texture = <LastPass>; MipFilter = LINEAR; MinFilter = LINEAR; MagFilter = LINEAR; AddressU = CLAMP; AddressV = CLAMP; AddressW = CLAMP; }; //----------------------------------------------------------------------------- // Vertex Definitions //----------------------------------------------------------------------------- struct VS_OUTPUT { float4 Position : POSITION; float4 Color : COLOR0; float2 TexCoord : TEXCOORD0; float2 PrevCoord : TEXCOORD1; }; struct VS_INPUT { float3 Position : POSITION; float4 Color : COLOR0; float2 TexCoord : TEXCOORD0; }; struct PS_INPUT { float4 Color : COLOR0; float2 TexCoord : TEXCOORD0; float2 PrevCoord : TEXCOORD1; }; //----------------------------------------------------------------------------- // Phosphor Vertex Shader //----------------------------------------------------------------------------- uniform float2 ScreenDims; uniform float2 TargetDims; uniform bool Passthrough; VS_OUTPUT vs_main(VS_INPUT Input) { VS_OUTPUT Output = (VS_OUTPUT)0.0; Output.Position = float4(Input.Position.xyz, 1.0); Output.Position.xy /= ScreenDims; Output.Position.y = 1.0 - Output.Position.y; // flip y Output.Position.xy -= 0.5; // center Output.Position.xy *= 2.0; // zoom Output.TexCoord = Input.TexCoord; Output.TexCoord += 0.5 / TargetDims; // half texel offset correction (DX9) Output.PrevCoord = Output.TexCoord; Output.Color = Input.Color; return Output; } //----------------------------------------------------------------------------- // Phosphor Pixel Shader //----------------------------------------------------------------------------- uniform float DeltaTime = 0.0; uniform float3 Phosphor = float3(0.0, 0.0, 0.0); static const float F = 30.0; float4 ps_main(PS_INPUT Input) : COLOR { float4 CurrY = tex2D(DiffuseSampler, Input.TexCoord); float3 PrevY = tex2D(PreviousSampler, Input.PrevCoord).rgb; PrevY[0] *= Phosphor[0] == 0.0 ? 0.0 : pow(Phosphor[0], F * DeltaTime); PrevY[1] *= Phosphor[1] == 0.0 ? 0.0 : pow(Phosphor[1], F * DeltaTime); PrevY[2] *= Phosphor[2] == 0.0 ? 0.0 : pow(Phosphor[2], F * DeltaTime); float a = max(PrevY[0], CurrY[0]); float b = max(PrevY[1], CurrY[1]); float c = max(PrevY[2], CurrY[2]); return Passthrough ? CurrY : float4(a, b, c, CurrY.a); } //----------------------------------------------------------------------------- // Phosphor Technique //----------------------------------------------------------------------------- technique DefaultTechnique { pass Pass0 { Lighting = FALSE; VertexShader = compile vs_2_0 vs_main(); PixelShader = compile ps_2_0 ps_main(); } } I tried changing this section as follows, but all I think this did was affect the phosphor trail persistence instead of the brightness (or maybe both?) The persistence itself is definitely shorter now. The brightness of the trails I am unsure about because they are so short I cannot tell. Any ideas? // Now blend, starting the trails at 45% brightness float a = max(PrevY[0] * 0.45, CurrY[0]); float b = max(PrevY[1] * 0.45, CurrY[1]); float c = max(PrevY[2] * 0.45, CurrY[2]); One thing you could try to do would be to lower the alpha channel output, assuming you have blending enabled on the sampler. Something like: return Passthrough ? CurrY : float4(a, b, c, CurrY.a * 0.5f); This would technically change the alpha of the entire output display (judging by where you placed the code change). I actually did try alpha changes earlier in the code when the trails were being blended, and the result was that the persistence seemed affected as well. I don't know what is going on.
common-pile/stackexchange_filtered
\0 values in Python dataframes I have a dataframe column called amount in python containing null and "\0" values. I want to convert this null and \0 values into \u0000 string function replace worked for null values. but for \0 values its not working. here is the example of my data. amount null "\0" "\0" "\0" "\0" "\0" I check the datatype using df['amount'].dtypes and it is string. why i cant replace the value? I had try using str.replace("\0", "\u0000") but its not working. Please create a Minimal, Complete, and Verifiable example What return df['amount'].head().tolist() ? @jezrael they return Out[326]: ['\0', '\0', '\0', '\0', '\0'] @Ducker - How working str.replace("\\0", "\u0000") ? @jezrael it produce result like this '\0' @Ducker - for me working df['amount'].str.replace(r"\\0", r"\\0000") in python 3 For me working: df['amount'].str.replace(r"\\0", r"\\0000")
common-pile/stackexchange_filtered
Regex (Java): Parsing a list of strings following a certain keyword I have a configuration file that contains a list of keywords. Following each keyword is a block that contains one or more values, each of which is surrounded by quotes. For example: SrcDir { "D:\Temp\Input\" } WorkDir { "D:\Temp\Work\" } Folders { "Standard Color Workflow" "Normal" "Fast" } I am trying to write a regular expression that will return as a capture group the keyword and then a list of its corresponding value(s). I started out using ([\w]+)\s\{([^}\n]+)}\n but it obviously doesn't work on the Folders section of the above sample, nor can this regex return multiple values even if they're all on the same line. Any help with this would be greatly appreciated. Which regex library you're using? Java regex? You're basically there. You just need to eliminate your \n references. As in: ([\w]+)\s\{([^}]+)} Now, that means in the third case, that all those fields will have their \n's embedded inside the captured group. Although now, I see you have a comment about "nor can this regex return multiple values even if they're all on the same line". So, perhaps I'm not understanding your problem. --- EDIT: To get each of these into their own capture group, To specify the quotes out separately. Try this: ([\w]+)\s\{(\s*"([^}"]+)"\s*)+} -- doesn't work --- EDIT 2: My example of getting them each into their group doesn't work. And it won't. StackOverflow: 5018487. I suggest using my original regex, take the complete set of strings found inside the {'s and then do a second regex search on that matched text to pull out each "text". Thanks, I learned something today! Ok, that's close. Is there any way to have the regex split up the values into their own capture groups? In order words, the three values in the Folders group would be their own capture group, and any white space between them removed? I tried something similar to that, but it only ever returns the last item in the list (e.g. "Fast" in the Folders example). Ok, I see that it can't work. I appreciate you looking into this, Mike. I will work on implementing your suggestion. Thanks much -- And welcome to stackoverflow. The etiquette here would be to accept the answer. Increases both our reps, and encourages others to answer further questions of yours.
common-pile/stackexchange_filtered
React Native bunch of buttons on top of background image I have a background image and I need to add bunch of oval buttons or images on in my case the "greenish" buttons on top of the background image, that I can click in each one of them and call a function passing a parameter. Please look on the screen shot and let me know how I can position every one of the buttons on top of the image and access them with a click (onPress). I guess the only way is using flex box but I couldn't figure out the style for it. Thanks Just style all the green buttons on relatively to the image's boundaries with position: absolute. Percentage values for positioning should work, if your image scales properly on screen size change. Thanks Denialos. It works. It just a lot of work because the number of buttons.
common-pile/stackexchange_filtered
Moving multiple boxes in figure? I already have the functions required to drag and drop a single box in a figure in MATLAB. The code I wrote fills the figure with several boxes. With another loop I filled the figure with more boxes (which hold different information in string form). These two sets of boxes are related by the numbers I placed in their UserData (corresponding numbers; for each box, there's another with the same UserData content). By finding boxes containing the same UserData (and thus relating them) I want to be able to relocate a member of the first set of boxes to the same position relative to the corresponding member of the second set of boxes, by means of right clicking on the box I just dragged (uicontextmenu). function recallfcn(hObject,eventdata) for ydx=1:2 diag_detail=get(gco,'UserData'); % This line should be in the drag fcn diag_pos=get(gco,'Position'); % So should this one (for current objects) xvar=diag_pos(1,1); yvar=diag_pos(1,2); detail=[diag_detail ydx]; set(findobj('UserData',detail),'Position',[xvar+(ydx-1.5) yvar+0.5 0.8 0.8]); end end % ydx is only there to add another level of detail as I'm actually looking to move % two boxes of the 'first kind', each of which have 2 numbers in user data, the first % number being the same, and the second number distinguishing the first box from the % second. The premise is the same. Yes, it should work as you described. So what's the question? When I right click on a box I'm using its handle. Once I move a member of the second set of boxes I use the function findobj(.) which is supposed to return a handle of the other box (the one I want to relocate relative to the first one I mentioned). There seems to be some kind of clash due to the fact that two handles are in use, and the code does nothing - returning no error message, either. I'll edit the question to include some of the code which I hoped to use for the relocation. I usually use findall instead of findobj, in case the handles of the objects are not visible from the outside. Other than that I don't see why your code wouldn't work. Here's an example: %# make a figure with two buttons, same userData fh=figure, uicontrol('userdata',[2 3],'parent',fh) uicontrol('userData',[2 3],'units','normalized','position',[0.5 0.5,0.1 0.1],'parent',fh) %# change color to red set(findall(fh,'userData',[2 3]),'backgroundcolor','r') %# move to the same position set(findall(fh,'userData',[2 3]),'position',[0.3,0.3,0.1,0.1]) As Jonas alludes to, the 'HandleVisibility' property of an object will determine if the object shows up in its parent's list of children, and thus if it will be returned by functions like FINDOBJ. The standard fix is to use the function FINDALL instead. However, the 'HandleVisibility' property also comes into play in determining whether or not an object can become the current object (i.e. returnable by the function GCO). If it is set to 'off', then that object can't become the current object. Additionally, if the 'HandleVisibility' property of the parent figure of an object is set to 'off' then none of its children (including said object) can become the current object. If 'HandleVisibility' is set to 'on' or 'callback' for all your objects and figures, then I think everything should work fine. Thanks, the explanation along with Jonas' example helped me understand a bit more about handles in MATLAB. you should inverse the ordre of x and y vector, and you can use just one loop, the changment in your code is : x2=x(end:-1:1); % invers the ordre y2=y(end:-1:1); for i=1:length(x) set(hLine,'xdata',x(i),'ydata',y(i)); % move the point using set % to change the cooridinates. set(hLine2,'xdata',x2(i),'ydata',y2(i)); M(i)=getframe(gcf); end
common-pile/stackexchange_filtered
getting following warning in android application I am developing an android application in which i have to remove the warnings,But when i try to run the code following warnings are generated,Can anyone help me 07-19 12:17:16.681: WARN/ImageView(4551): android.content.res.Resources$NotFoundException: Resource ID #0xffffffff 07-19 12:17:16.681: WARN/ImageView(4551): at android.content.res.Resources.getValue(Resources.java:892) 07-19 12:17:16.681: WARN/ImageView(4551): at android.content.res.Resources.getDrawable(Resources.java:580) 07-19 12:17:16.681: WARN/ImageView(4551): at android.widget.ImageView.resolveUri(ImageView.java:489) 07-19 12:17:16.681: WARN/ImageView(4551): at android.widget.ImageView.onMeasure(ImageView.java:592) 07-19 12:17:16.681: WARN/ImageView(4551): at android.view.View.measure(View.java:8171) 07-19 12:17:16.681: WARN/ImageView(4551): at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:578) 07-19 12:17:16.681: WARN/ImageView(4551): at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:362) 07-19 12:17:16.681: WARN/ImageView(4551): at android.view.View.measure(View.java:8171) 07-19 12:17:16.681: WARN/ImageView(4551): at android.widget.ListView.setupChild(ListView.java:1878) 07-19 12:17:16.681: WARN/ImageView(4551): at android.widget.ListView.makeAndAddView(ListView.java:1805) 07-19 12:17:16.681: WARN/ImageView(4551): at android.widget.ListView.fillSpecific(ListView.java:1347) 07-19 12:17:16.681: WARN/ImageView(4551): at android.widget.ListView.layoutChildren(ListView.java:1633) 07-19 12:17:16.681: WARN/ImageView(4551): at android.widget.AbsListView.onLayout(AbsListView.java:1280) 07-19 12:17:16.681: WARN/ImageView(4551): at android.view.View.layout(View.java:7035) 07-19 12:17:16.681: WARN/ImageView(4551): at android.widget.FrameLayout.onLayout(FrameLayout.java:333) 07-19 12:17:16.681: WARN/ImageView(4551): at android.view.View.layout(View.java:7035) 07-19 12:17:16.681: WARN/ImageView(4551): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249) 07-19 12:17:16.681: WARN/ImageView(4551): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125) 07-19 12:17:16.681: WARN/ImageView(4551): at android.widget.LinearLayout.onLayout(LinearLayout.java:1042) 07-19 12:17:16.681: WARN/ImageView(4551): at android.view.View.layout(View.java:7035) 07-19 12:17:16.681: WARN/ImageView(4551): at android.widget.FrameLayout.onLayout(FrameLayout.java:333) 07-19 12:17:16.681: WARN/ImageView(4551): at android.view.View.layout(View.java:7035) 07-19 12:17:16.681: WARN/ImageView(4551): at android.view.ViewRoot.performTraversals(ViewRoot.java:1045) 07-19 12:17:16.681: WARN/ImageView(4551): at android.view.ViewRoot.handleMessage(ViewRoot.java:1727) 07-19 12:17:16.681: WARN/ImageView(4551): at android.os.Handler.dispatchMessage(Handler.java:99) 07-19 12:17:16.681: WARN/ImageView(4551): at android.os.Looper.loop(Looper.java:123) 07-19 12:17:16.681: WARN/ImageView(4551): at android.app.ActivityThread.main(ActivityThread.java:4633) 07-19 12:17:16.681: WARN/ImageView(4551): at java.lang.reflect.Method.invokeNative(Native Method) 07-19 12:17:16.681: WARN/ImageView(4551): at java.lang.reflect.Method.invoke(Method.java:521) 07-19 12:17:16.681: WARN/ImageView(4551): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858) 07-19 12:17:16.681: WARN/ImageView(4551): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 07-19 12:17:16.681: WARN/ImageView(4551): at dalvik.system.NativeStart.main(Native Method) Thanks in advance Looks you've deleted a resource file and did not clean your project, so the mention of this resource in R file remained. Try cleaning your project. @egor i have cleaned the project,,,,,the code is very large,,,,,, Looks like you are trying to grab a resource with the same value as WHITE in ARGB! Check for any lines of code where you are trying to directly grab a colour value as a resource (in this case 0xFFFFFFFF) where it should be referenced as R.color.[your-colour]. I'm guessing this issue is most likely in a piece of code that tries to set the background of a view (receiving an int and hence looking for a resource). Add 0xFFFFFFFF as R.color.white and use that as the resource identifier. Not sure about this but it looks like you've set the source of an ImageView as white which is strange. You should look at the code. Never edit the R.java file, it is auto-generated. The problem is you are LOOKING for 0xFFFFFFFF somewhere in the code and that doesn't exist. Coincidentally 0xFFFFFFFF is also white, so you were trying to set something to white in the wrong place (or wrong way). I can't really help much further. i agree with your point,now 0xFFFFFFFF is not available in my code,,,so what should i do? the value is -1 and it's not a color, it's a resource id, somewhere in the code there is a reference to resource id -1 that some api may return as not found
common-pile/stackexchange_filtered
Block encapsulation vs. local encapsulation - let When I have data relevant to a function that is independent of its arguments, when should I favor block encapsulation over local encapsulation? When should I use: (let [hello "Hello "] (defn do-greet "Print a greeting." [name] (println (str hello name)))) Versus: (defn do-greet "Print a greeting." [name] (let [hello "Hello "] (println (str hello name)))) The former is a reasonable option if you want to use the value like a static constant within a lexically scoped block of code. Typically you would do this if: The value is expensive to compute, and you want to do it only once when the namespace is loaded The value is genuinely constant, i.e. will not change across function invocations The value will be used across multiple function definitions (i.e. you put multiple defns inside the let block) (Possibly?) because you want to use the value inside a macro expansion, and embedding the let inside the macro expansion itself would add unnecessary complexity. The latter version should probably be preferred in most other cases, it is good for several reasons: It is more idiomatic It allows the function definition to be at the top level, which is better for code readability / comprehension It allows the value to vary on different function invocations It better reflects the intent of using the value in a local context I like this, you cover more points. I'm not sure your macro expansion point is valid since you can wrap the let around the expansion but still be inside the function. For readability, I suggest separating stylistic choices from semantic differences. (Value can vary on different function invocations). It's a stylistic choice, and one that should probably depend at least a little on how expensive the value is to compute. Consider instead: (defn nth-prime [n] ...) (defn f [x] (let [factor (nth-prime 10000)] (* x factor))) (let [factor (nth-prime 10000)] (defn g [x] (* x factor))) Recomputing an expensive constant every time f is called is wasteful, and g uses a simple technique to avoid doing it. By saying there is a difference in runtime behavior (performance), I'd argue its NOT a stylistic choice. Only because in the asker's example, there is practically no difference, that it is stylistic. If hello is only used in that one single function, it makes more sense to put the let inside the function itself. If you were going to be using hello in multiple functions, it'd make sense to have the let outside of and wrapped around those functions. If the two are not equivalent at runtime, I'd argue that we should not be deciding just based on style. Imagine instead that the binding was to read a static resource (let [hello (slurp (clojure.java.io/resource "hello"))] ...). I've left my question more general because I don't know how those forms actually evaluate and what the corresponding tradeoffs are. It doesn't really have anything to do with style in some cases. If you need the value to be available in two different functions, you have to make the value available above the scope of those functions. Also, see @amalloy's answer. Definitely this: (defn do-greet "Print a greeting." [name] (let [hello "Hello "] (println (str hello name))))
common-pile/stackexchange_filtered
How to get a command variable inside another command variable? Example here: gitrepo=$(jq -r '.gitrepo' 0.json) releasetag=$(curl --silent ""https://api.github.com/repos/\"$gitrepo\""/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/') echo "$releasetag" Used \" to escape characters. 0.json: { "type": "github-releases", "gitrepo": "ipfs/go-ipfs" } How to put $gitrepo to work inside $releasetag? Thanks in advance! Bash variables expand inside quoted " strings. gitrepo="$(jq -r '.gitrepo' 0.json)" releasetag="$( curl --silent "https://api.github.com/repos/$gitrepo/releases/latest" \ | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/' )" echo "$releasetag" Btw, as you are using jq to extract .gitrepo from 0.json, you could also use it in the exact same way to extract .tag_name from curl's output (instead of using grep and sed) like so: gitrepo="$(jq -r '.gitrepo' 0.json)" releasetag="$( curl --silent "https://api.github.com/repos/$gitrepo/releases/latest" \ | jq -r '.tag_name' )" echo "$releasetag" And to simplify it even further (depending on your use case), just write: curl --silent "https://api.github.com/repos/$(jq -r '.gitrepo' 0.json)/releases/latest" \ | jq -r '.tag_name' Many thanks! Do you have a GitHub acc? I would like to add thanks No, I haven't but I appreciate it. :)
common-pile/stackexchange_filtered
WordPress/PHP: Split a post up into different pages or not depending on source For those who might don't know, in WP we can split up a post by adding <--nextpage--> where we would like our page breaks to appear. This will create a pagination where each section has its own page. What I want to do is, depending on the utm_source in the URL (ex: ?utm_source=fb) I want to have the pagination format to show, otherwise the one-page format will show. Put simply, if the source is FB, the <--nextpage--> in my post will be executed, or if the source is not FB, <--nextpage--> won't execute. I can do something with JS/JQuery if I only know how I can interact with the post content in the backend, not the end result that user can see. If it has to be done with PHP, I'm ready to learn to make it works. For those reasons I've no code to show for, but I've spent a lot of time looking for a solution with no success, unfortunately. WP determines & does the splitting of the content very early on. I eventually managed to get it to work by adding a action to the loop start to strip the nextpage comments if the source was not FB. \ Think carefully about whether you want to restrict this action from firing in any other situations, or restrict to only fire on certain posts. At moment it is going to try strip the nextpage on every post. function strip_next_tags_action () { global $post; // put any other if conditions here if ( !isset( $_GET['utm_source'] ) or !($_GET['utm_source'] == 'fb')) { $post->post_content = str_replace("<!--nextpage-->", "", $post->post_content, $count); } return $post; } add_action ('loop_start', 'strip_next_tags_action'); It's best done on the back end. You need to modify your single.php post template and use PHP code to display sections (or not) based on your query variables. Over-simplified example: <?php get_header(); if( !isset( $_GET['utm_source'] ) ) $_GET['utm_source'] = ''; switch( $_GET['utm_source'] ){ case 'fb': // do the Facebook stuff here the_excerpt(); break; case 'something-else': // do the other stuff here the_excerpt(); break; default: // if no matching utm_source variable, do this instead the_content(); } get_footer(); Thank you, Patrick, for taking the time to help me, it's appreciated. As said in my initial post, my main concern is how to change things in the backend which your code doesn't address. I want to know how to do the "do FB stuff" in your code. Thanks again. See my edited question, I had some formatting issues so some information where missing
common-pile/stackexchange_filtered
Active Directory PowerShell script permissions I'm newbie in PowerShell and scripting I need to write a script that: Lists all GPO's of the domain and checks the list for difference in param "Permission" to be "read" for concrete trustee. If the param "Permission" is for example empty or filled "write" instead of "read", it must change it to "read". I found a cmdlet in official Microsoft documentation, but it makes only input on console: Get-GPPermission -Name "TestGPO" -All Here's an example of how to check for specific permissions entries in all your GPOs: # put your AD group name here $target = 'ENTERPRISE DOMAIN CONTROLLERS' # iterate through all GP objects Foreach ($GPO in (Get-GPO -All)) { # get current permissions for GPO $Current = Get-GPPermission -Name $GPO.DisplayName -TargetName $target -TargetType Group -ErrorAction Ignore # check if current permissions exist and are correct if ($Current -and ($Current.Permission -eq 'GpoRead')) { Write-Host ($GPO.DisplayName + " permissions correct") } # otherwise, set corrected permissions Else { Write-Warning ($GPO.DisplayName + " permissions NOT correct") # example way to set or add permissions #Set-GPPermission -Name $GPO.DisplayName -PermissionLevel GpoRead -TargetName $target -TargetType Group } } # outputs like Default Domain Policy permissions correct Default Domain Controllers Policy permissions correct Bad-Policy permissions NOT correct However, be aware that all Authenticated Users already have Read and Apply access to all GPOs by default, so it may be better to search for Edit permissions and remove them instead (depending on your environment)
common-pile/stackexchange_filtered
Can i change/add logo in magento login page and backend page ? How? I have to change logo for existing magento login page and backend page with new one. Is there any function to change ? Here is login page image and backend page image : You want to change new logo in backend right Yes existing is old one i want to replace with new one ! Basic knowledge about the default logos:At first you have to know that there is not only one logo to replace in your store. By default Magento makes use of these 3 logos:Default Magento Header LogoThe logo in the header section of your store frontendDefault location: skin/frontend/default/YOURTHEME/images/logo.gifDefault Magento Email LogoThe logo in all transactional emailsDefault location: skin/frontend/default/YOURTHEME/images/logo_email.gifDefault Magento Print LogoThe logo in all printable documents like invoices and packing slipsDefault location: skin/frontend/default/YOURTHEME/images/logo_print.gifHow to replace all logos in your Magento storeThe easiest and fastest way to change all 3 default Magento logos is to replace the logos on your FTP server. To do that just login to your server using FTP and navigate to this folder: skin/frontend/default/YOURTHEME. There you find the following files:logo.giflogo_email.giflogo_print.gifYou can now replace the default logos by uploading your own logos with the same file names. Done! Now you see your own company logo on all mentioned places. OK, so far so good. But what to do if you don’t want to use a GIF but a PNG ot JPG? No problem!You can easily define the the logos for each of the 3 logos in your Magento backend.Change Header LogoUpload your own logo with your custom filename and extension to your FTP serverskin/frontend/default/YOURTHEME.In your Magento backend navigate to: System > Configuration > DesignIn the Header section you find all settings for the logo in your Magento store frontend.In the field Logo Image Src you can now replace images/logo.gif with your own filename like images/mylogo.png.Furthermore you can also define the alt tag of your logo image in the field Logo Image Alt.Change Email LogoIn your Magento backend navigate to: System > Configuration > DesignIn the Transactional Emails section you find all settings for the logo in your Magento Emails.Here you can easily upload your Email Logo in the field Logo Image.Furthermore you can also define the alt tag of your logo image in the field Logo Image Alt.Change Print LogoIn your Magento backend navigate to: System > Configuration > SalesIn the Invoice and Packing Slip Design section you find all settings for the logo in your printable documents.Here you can easily upload your Email Logo in the field Logo for PDF Print-outs (200×50) and Logo for HTML Print View.   Did not explain the backend logo. Login page logo is a background element in css file of your theme so this is the quickest way if you dont want to edit css file. To change logo in Login page, you need to upload and replace login_logo.gift in adminhtml/default/default/images/login_logo.gift For backend page, you can either upload/replace /skin/adminhtml/default/default/images/logo.gif or upload newlogo.gif and change the following line in /app/design/adminhtml/default/default/template/page/header.phtml $this->getSkinUrl('images/logo.gif') to $this->getSkinUrl('images/newlogo.gif') Hope this helps! Reference source: http://magentoexplorer.com/how-to-change-default-magento-logo-in-backend-and-frontend This solution gets overwritten on update, so it's not a recommended method. Best way is to create a custom module as explained here: https://stackoverflow.com/questions/16419081/how-can-i-change-logo-of-magento-in-backend. If you want to update/change logo from Magento backend (without using FTP) then you can do the following: Login to your Magento admin Edit any static block (CMS -> Static Blocks) There you will see Insert Image button. Click on it. Upload your logo image there. Suppose, your logo name is logo.png. Then, the image path will be http://your-website.com/media/wysiwyg/logo.png Now, go to System -> Configuration -> Design -> Header Update Logo Image Src to ../../../../../media/wysiwyg/logo.png. This has to be done because by default Magento fetches image from skin/frontend/smartwave/porto/images directory. Upload new logo in your skin folder then change image name here app\design\adminhtml\default\default\template\page.header.phtml <a href="<?php echo $this->getHomeLink() ?>"><img src="<?php echo $this->getSkinUrl('images/logo.gif') ?>" alt="<?php echo $this->__('Magento Logo') ?>" class="logo"/></a> Great, thanks but still not changing in login page! @BishalNeupane for login page upload new logo in your skin folder with name login_logo.gif skin/adminhtml/default/default/boxes.css change .login-container(background:url(enter url path)) Very Simple to change the magento backend logo. right click on the magento backend logo. click on ' copy image address' past it int he browser. you will get the exact logo address in the address bas. follow the path in file zilla and upload your logo through filezilla. None of the answers here give a proper solution. They either miss the point completely (the question is about the logos in the backend, not frontend) or they offer temporary solutions that only work until Magento is updated, at which point the custom files are overwitten and you are back to square one. The recommended method is to create a custom module, as explained in the accepted solution here: https://stackoverflow.com/questions/16419081/how-can-i-change-logo-of-magento-in-backend
common-pile/stackexchange_filtered
How to use deep linking and Apple App Site Association with React.js I have been looking far and wide and I can't seem to find any information about how to properly use apple-app-site-association/deep linking with a react.js website. I don't even have any code because I don't know where to start. @BennKingy I did. All I did was upload my react app to my hosting service, then put the file in the public_html folder. No extra steps. It was stupidly easy. Nice one! I got the devops guy to host the file in cloudflare at the root, bassicaly same as you. All good!
common-pile/stackexchange_filtered
How to skip 'die' in perl I am trying to extract data from website using perl API. The process is to use a list of uris as input. Then I extract related information for each uri from website. If the information for one uri is not present it dies. Some thing like the code below my @tags = $c->posts_for(uri =>"$currentURI"); die "No candidate related articles\n" unless @tags; Now, I don't want the program to stop if it doesn't get any tags. I want the program to skip that particular uri and go to the next available uri. How can i do it? Thank you for your time and help. Thank you, Sammed Well... not to be a smartass or anything, but if you don't want the program to die, dont use die? You can't have it both die and not die at the same time. @ TLP .Good one..the thing is I want to skip the error and move ahead, that is what I want to do.. Maybe just change the 'die' to 'warn'. Well, assuming that you're inside a loop processing each of the URIs in turn, you should be able to do something like: next unless @tags; For example, the following program only prints lines that are numeric: while (<STDIN>) { next unless /^\d+$/; print; } The loop processes every input line in turn but, when one is found that doesn't match that regular expression (all numeric), it restarts the loop (for the next input line) without printing. The same method is used in that first code block above to restart the loop if there are no tags, moving to the next URI. thank you for your answer. Yes, I am doing this inside a loop processing each URIs in while loop. I just want to confirm the syntax, will it be something like this: 'my @tags = $c->posts_for(uri =>"$currentURI"); next unless @tags;' Besides the traditional flow control tools, i.e. next/last in a loop or return in a sub, one can use exceptions in perl: eval { die "Bad bad thing"; }; if ($@) { # do something about it }; Or just use Try::Tiny. However, from the description of the task it seems next is enough (so I voted for @paxdiablo's answer). The question is rather strange, but as near as I can tell, you are asking how to control the flow of your current loop. Of course, using die will cause your program to exit, so if you do not want that, you should not use die. Seems elementary to me, that's why it is a strange questions. So, I assume you have a loop such as: for my $currentURI (@uris) { my @tags = $c->posts_for(uri =>"$currentURI"); die "No candidate related articles\n" unless @tags; # do stuff with @tags here.... } And if @tags is empty, you want to go to the next URI. Well, that's a simple thing to solve. There are many ways. next unless @tags; for my $tag (@tags) { ... stuff ... } if (@tags) { .... } Next is the simplest one. It skips to the end of the loop block and starts with the next iteration. However, using a for or if block causes the same behaviour, and so are equivalent. For example: for my $currentURI (@uris) { my @tags = $c->posts_for(uri =>"$currentURI"); for my $tag (@tags) { do_something($tag); } } Or even: for my $currentURI (@uris) { for my $tag ($c->posts_for(uri =>"$currentURI")) { do_something($tag); } } In this last example, we removed @tags all together, because it is not needed. The inner loop will run zero times if there are no "tags". This is not really complex stuff, and if you feel unsure, I suggest you play around a little with loops and conditionals to learn how they work. @TLP..Thank you for your answer. Well, I am learning a bit of the conditions and loops. I think I am getting to it. Thank you for your help.
common-pile/stackexchange_filtered
Can I do Contract.Ensures on IQueryable and IEnumerable? Lets see this code: public IQueryable<Category> GetAllActive() { Contract.Ensures(Contract.Result<IQueryable<Category>>() != null); return dataSource.GetCategories(T => T.IsActive); } There is a small question. Is it okay with code contracts write this: public IQueryable<Category> GetAllActive() { Contract.Ensures(Contract.Result<IQueryable<Category>>() != null); Contract.Ensures(Contract.Result<IQueryable<Category>>().All(T => T.IsActive)); return dataSource.GetCategories(T => T.IsActive); } Or not? Will such a thing produce the unnecessary sequence enumeration, which is highly undesireble? If you're using the full runtime contract checker, I fail to see how it can avoid forcing enumeration to occur - how else could it check it? @Damien_The_Unbeliever It couldn't. And I am not using runtime checker. For me, right now, the contracts is a way let the tools to test my code for simple possible logic conflicts. So you need to clarify which parts of the contracts system you're using, if you want a clear answer. There are lots of options that can be turned on. @Damien_The_Unbeliever I use only the static checker. Assuming you're using the binary rewriter and enforcing contracts at runtime, you should not do this. When you use Contract.Ensures like so: Contract.Ensures(Contract.Result<T>() <operation>); return expression; It's transformed and the operation is lifted into something like the following: T expression = <expression>; // Perform checks on expression. if (!(expression <operation>) <throw appropriate exception>; // Return value. return expression; In this case, it means that your code unwinds to: IQueryable<Category> temp = dataSource.GetCategories(T => T.IsActive); // Perform checks. if (!(temp != null)) throw new Exception(); if (!temp.All(T => T.IsActive)) throw new Exception(); // Return values. return temp; In this case, your IQueryable<Category> will be iterated through and will cause another request to be sent to the underlying data store. Depending on the operation, you might not notice it, but the query is definitely going to be executed twice and that's bad for performance. For things of this nature, you should check at the point of consumption of the IQueryable<T> whether or not you have any elements (you can do it with a boolean flag that is set as you foreach through it, or when you materialize it). However, if you are not running the binary rewriter on your compiled assemblies, then Contract.Result<T> contracts of this nature cannot be enforced; in this case, it's a noop and probably shouldn't be there, as it's not doing anything.
common-pile/stackexchange_filtered
Gauss Elimination for Colorability Problem Consider the following system of linear equations modulo 2: $A.X + B.Y = Z, $ where $A$ is a non-singular(modulo 2) $n$ x $n$ boolean matrix, $B $ is $n$ x $m$ boolean matrix, $X$ is n-dimensional boolean(unknown) vector, $Y$ is $m$-dimensional boolean(unknown) vector and $Z$ is $n$-dimensional boolean unknown vector. So, solutions of the equation above are pairs of boolean vectors $(X,Y)$. Prove that the number of solutions is equal $2^{m}$. Use this observation to get a polynomial time algorithm to count a number of 2-colorings. I see that the products are defined. We would end up with $Z$ as a (nx1) vector that I assume is mod2 as well. All possible combinations of this boolean solution is $2^{n}$. I don't know why the question state it as $m$. Apparently, I need to use the Gauss elimination algorithm for 2-colorability in order to solve this problem. Any ideas? Thank you. Since $A$ is non-singular the equation is equivalent to $X = A^{-1}(Z-BY)$. So, for any choice of $Y$ you get a solution to the system. So, the number of solutions is the same as the number of possible $Y$. That is $2^m$. Thank you. It's a very nice observation and shows my rusty Algebra. However, I am still confused about, "Use this observation to get a polynomial time algorithm to count a number of 2-colorings." I guess that the connection between a 2-colorability graph problem and the matrix is because of mod2 constriction? I know that the 2-coloring problem reduces to a decidable problem iff the graph is bi-partite or not; this takes polynomial time. ' What is the precise statement of "count a number of two coloring" problem? Yes, I don't understand the statement either. I can only guess what the problem means, I could state some algorithm for decidability of a bi-partite graph. But, I am not fully sure what the "count a number of two coloring" statement means. I think that the statement refers to specific colorability and linear algebra differences. For Linear Algebra, vector [1 0 0] is different than vector [0 1 0], but for graph-colorability theory both vectors represent 3 colorability valid vectors. So, I think the question of counting a number of 2-colorings refer to find values of Y that are valid for colorability. What kind of 2-coloring are you considering? If you are considering proper vertex 2-coloring, then any connected bipartite graph has exactly 2 proper colorings. However, if you are considering any 2-coloring, them the number is $2^k$ where $k$ is the number of vertices of the graph. I am not considering any color, but that's a good point. Can I work the problem out without considering a specific color?
common-pile/stackexchange_filtered
How to match everything between strings including multiple lines? I'm writing my own template engine and I'm working on the loop part, I thought I should use regex to help me match whatever loops there are in the template I came up with the following {foreach \$list as \$item}(.+?)${\/endforeach}\s I need it to match everything between those two strings and those two strings as well, so if my text was <html> <head> <title>Test</title> </head> <body> {foreach $list as $item} <td>{$item}</td> {/endforeach} </body> </html> I need it to match {foreach $list as $item} <td>{$item}</td> {/endforeach} However the regex that I wrote is matching it until a new line happens then it stops matching even though I use \s Does anyone know what's going wrong? /{foreach \$list as \$item}(.+?){\/endforeach}/s. Check it out https://regex101.com/r/hB6zC0/1 @HamZa Thanks a lot. However, can you explain to me what I've been doing wrong? You need to specify delimiters: it can be /, #, ~ and much more. It will look like /regex/. Then you need to add the s modifier to match newlines with . (dot): /regex/s. You wrote \s which means "match a white space". I also removed $ after (.+?) since it means end of string.
common-pile/stackexchange_filtered
scheme: how to use call/cc for backtracking I have been playing around with continuations in scheme (specifically guile) over the last couple of days and am a little puzzled by the results that some of the functions have and was wondering if anyone could explain exactly what is going on here. There is a function called (get-token) that will retrieve the next found token in a given file. For example, if the next 3 tokens were "a", "b", and "c", calling (get-token) would return "a" the first time it is called, "b" the second time it is called, and "c" the third time it is called. What I would like to do is have a function (peek-token) that will call (get-token), return the token, and then return to a state before the (get-token) function was called. I have attempted a number of different methods to achieve this result, and the one I currently have is: ;; make things a little easier to write (define-syntax bind/cc (syntax-rules () ((bind/cc var . body) (call/cc (lambda (var) . body))))) ;; function should return next token and then ;; revert to previous state (define (peek-token) (bind/cc return (let ((token (get-token))) (return token)))) How I understand it right now, the bind/cc will save a continuation at the first return and then execute the following block of code. Then when return is hit again, the program jumps back to where the continuation was bound and the token value is given as a result. However, when I run the above function the results are exactly the same as the original (get-token) function. I would be very grateful if anyone could explain where I am going wrong, or express a better way to get the same result (I know some people hate going the way of call/cc). To hack a Mark Twain misquote to pieces: The reports of call/cc's capabilities are greatly exaggerated. More specifically, call/cc captures call state, not program state. That means that it captures information about where the flow of code goes when the continuation is invoked. It does not capture information on variables, and in particular, if your get-token saves its iteration state by set!ting a variable, that is not going to be restored when you invoke your continuation. In fact, your expression of (call/cc (lambda (k) (let ((token (get-token))) (k token)))) should behave identically to simply (get-token); there should not be any observable differences between the two expressions. Thanks a ton for clearing this up. I ended up putting the (peek-token) function inside of my scanner file and am just keeping track of the file pointer so I can re-read tokens from it. Just out of curiosity, do you know of a way to capture the actual program state in either scheme or CL? Or is there never really a need for this? Unless I'm mistaken anything of the form (call-cc (lambda (k) ... (k x))) is exactly the same as (begin ... x). @jozefg Pretty much, assuming that that's the only place the continuation is used.
common-pile/stackexchange_filtered
Text overflows image I'm making a project were i make a video out of reddit post, part of it is getting a paragraph and adding a background image to it, i found out I could do it with pillow but my text overflows. Code: from PIL import Image , ImageDraw, ImageFont text = "Some background: my friend lost her father and her two older sisters in a tragic car accident 7 years ago. " \ "I was her shoulder to cry on. She became attached to me as a second sister " \ "and grew closer to her only living sibling (her brother)." new = Image.new('RGB', (1000, 1000), color=(3, 252, 232)) d = ImageDraw.Draw(new) fnt = ImageFont.truetype("comicbd.ttf", 25) d.text((0, 0), text, font=fnt, fill=(255, 255, 255)) new.show('img.jpg') image of overflow: Does this answer your question? How to add text in a "textbox" to an image? ... PIL - draw multiline text on image, Wrap text in PIL, Break long drawn text to multiple lines with Pillow I think textwrap is builtin and can be used like textwrap.wrap(str, len) Atleast when I tried this using moviepy this was my easiest solution
common-pile/stackexchange_filtered
Apple Pay on web using stripe.js, populating the popup I am testing the Apple Pay JS, I have it working completely. However, I would like to populate the confirmation popup (the one that asks to accept the purchase) with some other fields, like user's name or address. The documentation says it can be done, but there are no examples. Here is the code I am referring to: var request = { countryCode: 'US', currencyCode: 'USD', supportedNetworks: ['visa', 'masterCard'], merchantCapabilities: ['supports3DS'], total: { label: 'Your Label', amount: '10.00' }, } var session = new ApplePaySession(1, request); This can most certainly be done. The PaymentRequest object allows you to include a shippingContact object that is a shipping dictionary. The available fields are listed on their PaymentContact page. So your PaymentRequest will look like var request = { countryCode: 'US', currencyCode: 'USD', supportedNetworks: ['visa', 'masterCard'], merchantCapabilities: ['supports3DS'], total: { label: 'Your Label', amount: '10.00' }, shippingContact: { givenName: 'Martin', familyName: 'StackOverflow', addressLines: ['123 Main St', 'Apt: 5'], locality: 'Whoville', administrativeArea: 'FL', postalCode: '43210', country: 'US' } } var session = new ApplePaySession(1, request); When you pass this information to the PaymentRequest, that address will show up in the Paysheet. It will not add the contact to their list of contacts, and they can still overwrite it with their own contacts, but that address will be what shows in the Paysheet by default. As far as I'm aware you cannot write contact information to the Apple Pay sheet using the JavaScript API, only read the values the user has entered back. Pre-propulated values come from the phone from details entered for the user's previous Apple Pay sessions, whether on the web or in apps, are then saved into Wallet by the device. You can read some of the contact details from the event passed to the onshippingcontactselected function, with everything being returned in the event passed to the onpaymentauthorized function.
common-pile/stackexchange_filtered
Studying the nature of the world: philosophy or physics I must say this is a topic that's been bothering me for some time now, especially considering my confusion of current state of academic departments. Put simply, I understand while reading philosophy of nature (the older term, I think, of nowadays physics) that the study of nature of the world (i.e. cosmology, parts of metaphysics, etc) used to lie in the philosophy department. But nowadays it seems as though philosophy stopped studying such subjects (or at least most of it, as subjects such as philosophy of mind still exists), and now the department that studies them is mostly physics. Correct me if I'm wrong, but by that development, the conclusion to a student interested in (what used to be) "philosophy of nature", is that he should study physics, and not philosophy (perhaps some combination, but physics would be the dominant one). Is that conclusion the correct one? Note that this is purely practical question. [I had no idea which tag would fit, so edit if you have any suggestion.] Edit: While looking at the answers a thought came into my mind - most of the answers say something like "you can't not do both, it'd be way less effective". If so, why there are so many physicists that don't study philosophy? Why, for example, are there no philosophy courses in the physics degree? Are they being ignorant of philosophy? Do they think physics is inherently enough? Or do they simply don't interact with philosophy to even know its necessity? You are talking about Natural Philosophy. It was a precursor to Natural Science. So, yes, if you want to study that which was studied under "Natural Philosophy", then physics — or any other one of the natural sciences — is where place to go. Modern philosophy is not related to that which was Natural Philosophy. They are just named similar. As scientific knowledge has expanded, it has tended to raise philosophical questions not previously mooted, and inform the debate over others. If these issues interest you, then having a working understanding of relevant scientific knowledge is a prerequisite. "Nature of the world" is a pretty high-minded term, taken at face value it is certainly beyond physics. I do not think one can avoid having a solid background in modern physics to credibly philosophize about it (thinking otherwise was, I believe, the cardinal mistake of "old" Naturphilosophie), but things like interpreting quantum field theory or speculating about string theory ontologies build on it as only a foundation. The term is philosophy of physics, and Princeton's Halvorson has a guide for those aspiring to engage in it RE: Physicists studying philosophy, I suppose this is one reason the Physics department at UC Berkeley is in the College of Letters and Sciences, which has a large body of general-education requirements (philosophy classes satisfy some of them)... the Engineering school and the College of Chemistry have fewer such requirements, I think. IMO, your conclusion is correct: If you are interested in a philosophical worldview based on science, in particular on physics, the best way is to take physics as major and philosophy as a minor. And do not restrict the subject to philosophy of science. Without doing some pyhsics by yourself you will not be able to assess the weight of physical insights which are the subject of philosophical considerations. But physics is a long and difficult study, it starts with mathematics, and there are no shortcuts on this way. Nevertheless the fruits are very rewarding. The study of physics brings you in contact with some of the greatest insights in the history of science. Possibly you will enjoy on your way also some other scientific domains which contribute to a modern worldview, e.g. neuroscience. Many philosophers of physics and quite a few theoretical physicists don't see a bright line between the two fields. Philosophers of physics often have at least an undergraduate degree in physics and regularly attend physics conferences; some also collaborate with theoretical physicists. Many physicists are hostile to philosophy, either because of a "shut up and calculate" attitude or because they're ignorant about philosophy. But other physicists enjoy engaging with philosophers. For example, a friend of mine is a philosopher of cosmology. She's currently finishing up a postdoc that was jointly supervised by a philosopher of science and an astrophysicist. During her postdoc, she was trained how to take observations at a telescope in South America and wrote a few papers on dark matter with the astrophysicist and other members of his team. From this perspective, you don't necessarily have to choose between physics and philosophy of physics. If you're putting together a reading list for your own personal edification, then feel free to read books and papers from both. If you're trying to choose an undergraduate degree, then double major (in North America) or look for a program of study that includes both physics and philosophy. If you're trying to choose a graduate degree, the institutional difference is more important — career trajectories and opportunities can be very different. In that case, look for programs and particular advisors who regularly collaborate across the disciplinary divide and have a strong record of placing recent graduate students in the kind of academic career you're interested in. Reach out to them by email to get more information about the program, their current research interests, whether you might be a good fit, and so on. I like this answer a lot as it pans out all the practical consequences. Thanks! Regarding another comment from here, in many cases yes, physicists have absolutely no interest in philosophy, but that's not too relevant for the ones that do, like the author here, myself or many others. I'm a researcher with doctor's degree in physics and I like philosophy a lot, I even hold philosophy seminars. Generally speaking, when in physics you get to a halt given by an absurdity, it's best that you use logic and philosophy to be able to be out-of-the-box. Otherwise, you may be stuck in a no-solutions loop. You end up with theories supported by absurd math that have no practical application or value whatsoever. The impasse in physics today is the result of false premise, and only doing textbook physics it's very unlikely that one realizes that. Philosophy can help and it did for many researchers, including my own teams. We were able to study physical aspects from a non-standard perspective and to come up with new valid theories, mathematically proved and experimentally confirmed, which contradict some theories widely accepted with the difference that the new ones can explain way more than the old ones. From a difficulty perspective, studying physics is significantly harder than studying something like philosophy. Therefore, if you want to approach both aspects, it's safe to say that your will need to invest longer time in the study of physics. Therefore, it would be good to do physics as official study while treating philosophy like a hobby, a way to relax. That's what I'd recommend after more than 20 years of activity in both fields. Physicists in general, have absolutely no interest in philosophy, or in doubting the foundations of how they know things. Even the philosophically inclined and capable like Einstein, generally fight for conservative positions rather than radical ones (look to Kuhn on why). Physics gets on with observations, experiments, and calculations. Philosophy, including philosophy of science and philosophy of physics, is about something else. These do cover what we know about the world, and how we know it, and how we should do the practice of physics. Crucially, more generally it is also a space for asking questions which cannot be settled by observations, experiments, and calculations. Many physicists feel such questions are intrinsically meaningless, or at least irrelevant. But that is because they are using the tools that have resulted from a settled consensus on the answers to many questions they don't consider, answers which they take for granted. In this age of dark matter and energy, of coming to recognise the huge challange of unifying the fundamental forces such as in addressing what time itself is, the foundations of physics have never needed questioning more. The current impasse is likely a result of the fact that the next places we need to go, are stranger than we can currently imagine. It will take more than just observations to get there. My apologies for a longish answer to this somewhat important question that addresses one of the challenges that faces serious students of science and philosophy today. Let us start from the beginning. The fields of science such as physics, chemistry, biology, etc. are specialized tools of human cognition. While there is some overlap in their domains of validity, it is not always clear how these domains ought to be defined, or whether it is even advantageous to draw hard inflexible boundaries between such fields of science. For example, there is some overlap between physics and chemistry, but it is arguably wiser to leave the boundary hazy so that both physics and chemistry can coexist and grow through a synergistic relationship. Also, the separation of domains between physics and chemistry is generally not considered a source of conflict because both physics and chemistry are fundamentally based on the same language of what is known as the scientific process, therefore the playing field is essentially the same, and the players think alike as they go about their specialized profession. In contrast, the gap between philosophy and physics (and science in general) has grown wider over the past centuries, as the great natural philosophers of the past remained in the past, and scientific progress continued to march forward fueling technological development on the basis of newer scientific theories which more and more were seen to rely less on a philosophical grounding, or at least so it seemed. Consequently, the important works of philosophers of science such as Karl Popper were largely ignored, because the subject of philosophy itself was no longer held in high esteem among modern scientists, being considered more a nuisance and an obstacle to scientific advancement rather than an enabler of novel scientific ideas. Philosophy had also lost the battle in the court of public opinion before the battle was even fought. How many philosophers of science have gained in the public limelight? How many philosophers of science have there been with tangible technological achievements to showcase? Philosophy was essentially relegated to the underground. Any prominent physicist who openly admitted to deriving inspiration from natural philosophy became a physicist who was taking a big risk of being ridiculed and ostracized. Who wants to commit professional suicide? So how does this translate to the way physics is practiced and taught in academic departments? Once the ideological fault line was drawn between philosophy and physics, translating this reality to everyday academic life became self-evident. Physics departments in general are highly conservative in terms of their zealous adherence to the currently accepted tenets and theories of physics. The academic survival of the members of the department is typically contingent on their ability to attract research funding. Imagine submitting a research proposal titled “The philosophical foundations of quantum mechanics”. One such proposal in the wrong department is enough to ruin an academic career and jeopardize the reputation of the department, so over time it is not hard to see why an academic department begins to operate like a financially motivated self-perpetuating business. Many students of physics therefore learn by example to steer away from philosophical subjects. So, how is a serious student of physics to study the wealth of knowledge accumulated in the field of natural philosophy without risking a career? Before addressing this challenge, it seems appropriate to keep in mind that both philosophy and physics have their unique utility, but that they are different in their methodological focus. Philosophy is entirely mental, with no objective tangible means of validating its ideas, while physics deals entirely in the physical realm of nature where theories can be subjected to experimental testing and validation, and subjected to the test of prediction. But can we do any physics without mental activity? Could there be any physical law without an underlying philosophical basis? It is unthinkable. Consider Newton’s famous three laws of motion. The great scientists of the past such as Newton were deeply inspired by what we nowadays call philosophy. Unfortunately, today’s new physics is losing touch with its philosophical foundations, but is this a wise direction to pursue? Ignoring the entirety of the philosophical method in the process of developing new theories of physics is like throwing the baby out with the bathwater, even though natural philosophy is really not the baby but more the mother of physics. Therefore, as the rift between philosophy and physics continued to widen, and as physics continued to eclipse philosophy on the stage of tangible achievements, the guiding principles as well as the checks and balances traditionally derived from philosophy also faded gradually. Physics had conquered the opposition, and was free to advance theories that were exclusively based on experimental empiricism. It seemed sufficient to ensure that any accepted theory of physics agreed with experimental data, and made the correct predictions. In time, there was nobody there to question the validity of the extrapolations that were born from an unguided interpretation of the meaning of the theories of physics. In effect, physics theories began to invent new natural philosophy. The cart was put ahead of the horse, and it seemed to matter little that the cart and horse were in a state of collective confusion. To answer the question, the perceived conflict between philosophy and physics appears to be a conflict between practitioners of science who are focused almost entirely in their own field of specialization, and therefore have little patience (or interest) in learning more about the philosophical method that they hardly hold in high regard. To them, philosophers “philosophize”, while physicists do the real hard work of theorization, computation and experimentation, which leaves little room or incentive for collaboration. True advancement and giant leaps in science (including physics) will likely come from those pioneering scientists who bucked the trend and have been able to derive practical knowledge from beyond the boundaries of science, and that includes natural philosophy. Those who have an inadequate foundation in the basic principles of nature, as elucidated in what was known as natural philosophy, run the risk of uttering nonsense and not know that what they are claiming is fantasy more than reality, while hiding behind the false comfort of the experimental validation of their theoretical models. It is seldom emphasized that all theories of physics (and science) are only mathematical models, and not to be misused to supersede the basic principles of physical reality. One such principle is causality. If one argues that something can happen from nothingness, who is to hold the person’s feet to the fire if all the philosophers have been silenced? Some of the interpretations that defy logic in today’s fundamental physics are simply illogical, and this is where natural philosophy could have provided the mental grounding through logic. If we stray too far in our flight of fantasy, who is to stop us if all the opposition has been silenced. Natural philosophy is a rich mental field from which to choose and pick the valuable plants that can be transplanted into science. Fundamental physics that is in stark contradiction to the basic principles of physical reality may well become a confused science barking up the wrong trees. My opinion that I would share with serious students of physics (and science) who seek to advance human knowledge through the scientific process is: if you are studying to become a physicist, by all means study natural philosophy perhaps as a hobby in your own time, and if you are a philosopher then good luck to you with studying physics on your own time because learning the methods of physics requires persistent dedication, which explains partly why physicists and philosophers find it hard to communicate constructively because they hardly speak the same language. Like our scientific pioneers, including Newton and Einstein, we have a lot to learn from observing and reflecting on the workings of nature, and what better name to call it but natural philosophy? Most historians of philosophy mark the beginning of science and philosophy at 585 BC when Thales of Miletus predicted an eclipse and claimed everything was made of water. From that point until about the 18th century, science was considered a branch of philosophy. ‘Natural philosophy,’ as you noted. Physics was the first area of research to formally break off from philosophy, and psychology was the most recent. Generally, when a branch of scientific research becomes sufficiently mature (or rather successful), it will break away from philosophy—or at least that is how the process is commonly described. Thomas Kuhn describes science as being organized into paradigms. Paradigms allow researchers to assume a certain common framework and avoid fundamental arguments of a more metaphysical nature. In this description, the breaking-away process can be thought of as the result of the formation of a paradigm. Before the formation of a paradigm there is massive disagreement at the most fundamental levels; after the formation of a paradigm, the answers to basic questions have been assumed, and researchers are now focused on filling in the details (at which point they get their own department). I'm a philosophy progressor at an R1 university, who majored in philosophy and mathematics, and considered going into pure mathematics instead of philosophy. Other people have made great points that I won't repeat. But I will say that, in contrast to some of the above commentators, I doubt there's a simple way to gauge the relative difficulty of the subjects. It might be true that getting a BA in physics is harder on average than getting a BA in philosophy. But, then, getting into a top PhD program in physics is probably easier than getting into a top PhD program in philosophy, if only because philosophy programs are dramatically smaller, and physics jobs are much more plentiful. All told, my guess is that making original contributions to philosophy that might get you desirable academic job is considerably harder than making original contributions to physics that might do this. It might be wiser, then, to go into physics than into philosophy, other things being equal. (This is similar to the refrain that there are practically no jobs in logic, and many of those are philosophy departments. So, if you're doing pure math, you're advised to do a 'core' subject like algebraic geometry if you hope to get an academic job.)
common-pile/stackexchange_filtered
ComboBox, very new to WPF I have a ComboBox bound to a collection of objects. The objects have property boolean IsSelected which specifies if the object is currently selected to show in ComboBox text area. In order to make it use the IsSelected boolean property to show default item in ComboBox, I added a ValueConverter class like below. public class SelectedItemConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value != null && value is IEnumerable<Car>) { return ((IEnumerable<Car>)value).Where(n => n.IsSelected).FirstOrDefault(); } return null; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value != null && value is Car) { return value; } return null; } } My ComboBox is in a UserContrl and its xaml is: <ComboBox ItemsSource="{Binding CarsList}" SelectedItem="{Binding CarsList, Converter={StaticResource selectedItemConverter}}" DisplayMemberPath="Name"> </ComboBox> I am using SelectedItem because my Car object has IsSelected which is boolean and it represents whether the Car is visible in ComboBox text area. For that reason, I have the ValueConverter above to use that boolean to properly return object. This works well and when ComboBox loads, the object that has IsSelected=True will show in ComboBox text area. However, if I expand dropdown and select another object, that object will show but ComboBox gets a red border which as far as I know means that there is some validation problem. How do I fix this? I have seen many examples but none of them are addressing the issue where a boolean property IsSelected is used to determine which object to show in ComboBox. How do I resolve this? Probably the problem is ConvertBack function, it should return IEnumerable<Car> CarsList. Anyway I think you should rethink abount binding to SelectedItem using that way. You are correct, the ConvertBack is returning Car instance and not CarList instance. But the problem is that I dont have CarList instance as it is not passed into the ConvertBack. So not sure how to get it to return it. I think @Bolu suggested good way how to change binding. Else you can try to pass CarList as a ConverterParameter (if CarList collection never changes you can define it in xaml like resource), but this is weird complicated way. CarList collection does not change but it is from a file. So, once form loads, CarList collection is loaded from a file and used by the ComboBox to allow user to select a Car. So, it does not change really but it has to come from a file. Would CoverterParameter still be an option and how to add it? Thanks, In WPF, a common practice of using ComboBox is as below: In the ViewModel Define collection as a property in your VM (as you did for CarsList) Define selected item as a property in your VM (use another property e.g.: SelectedCar) In the View Bind ItemsSource to the 'collection' property. Bind SelectedItem to the 'selected item' property. e.g. <ComboBox ItemsSource="{Binding CarsList}" SelectedItem="{Binding SelectedCar}" DisplayMemberPath="Name"> </ComboBox> If you want to set a default item for selection, you just set SelectedCar property to that item. And when user changed the selection, you will be able to always get the selected item from SelectedCar property. Edit: Simple working example: C#: using System; using System.Collections.Generic; using System.Windows; using System.ComponentModel; using System.Collections.ObjectModel; namespace WpfApplication1 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); MyViewModel mvm = new MyViewModel() { CarsList = new ObservableCollection<Car>() { new Car() { Name = "Car1" }, new Car() { Name = "Car2" }, new Car() { Name = "Car3" }, new Car() { Name = "Car4" } } }; this.DataContext = mvm; } } public class MyViewModel : ObservableObject { private Car _selectedcar; public ObservableCollection<Car> CarsList { get; set; } public Car SelectedCar { get { return _selectedcar; } set { if (value != _selectedcar) { _selectedcar = value; RaisePropertyChanged("SelectedCar"); } } } } public class Car : ObservableObject { private string _name; public string Name { get { return _name; } set { if (value != _name) { _name = value; RaisePropertyChanged("Name"); } } } } public class ObservableObject : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { var handler = this.PropertyChanged; if (handler != null) { handler(this, e); } } protected void RaisePropertyChanged(String propertyName) { OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); } } } XAML: <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="300" Width="300"> <StackPanel Orientation="Vertical"> <ComboBox ItemsSource="{Binding CarsList}" SelectedItem="{Binding SelectedCar}" DisplayMemberPath="Name"> </ComboBox> <TextBlock Text="{Binding SelectedCar.Name}"/> </StackPanel> </Window> Result: The text in TextBlock will update when the select of ComboBox changed. Would you mind elaborating bit more. Do you have any good example of ComboBox being used this way? Much appreciated Much appreciated Bolu. That is very helpful. I would use the ComboBox's SelectionChanged event to update the IsSelected property of each item in your bound list, setting only the new selection to 'True', and all others to 'False'. This means you won't need a converter, which @bars222 pointed out is currently not properly returning the type of enumerable that you're binding to. Note that this won't allow the ComboBox to update the selected item when you set an item's 'IsSelected' property to 'True' - but you should be making those changes by binding the combox's SelectedItem directly to a public SelectedCar property on ViewModel. When the view-model loads, you can initialize this SelectedCar by inspecting the list, and the appropriate item will be shown as selected. I am trying to figure out why is the converter not returning proper value. Thanks Andrew. It seems you would like to apply MVVM patterns to your design. I would suggest that you dont need a converter, you can manage your collection in your view model.
common-pile/stackexchange_filtered
Could ScheduledThreadPoolExecutor work on 2 tasks concurrently? In my code I use ScheduledThreadPoolExecutor initialized with pool size of 10 threads, and I have jobs that are being executed. In my logs I seem to see a problem where the same thread seems to be working on 2 different jobs concurrently !! Could this be?? How did you figure out that the same thread is executing two jobs concurrently? no, it can't - probably you have named the logger which you use to identify the threads using the same name. show us the code you should not be worrying about the thread of your pool. moreover, do you have evidences that 2 jobs (define jobs, btw) are being executed by the same thread at the same time. I know this because one task tries to lock for reading a ReentrantReadWriteLock lock and a different task tries to access the same lock but for writing. When the 2nd task tries to lock for writing I get a warning that tells me that the same thread already locked for reading!
common-pile/stackexchange_filtered
Tickera plugin Wordpress modify default form I am using Tickera plugin. The page which shows the tickets it's at example.com/tickets-cart/ . This page has a default form but i can't find a way to modify the specific form. This page looks like this : The content of specific page calls a shortcode [tc_cart] . Is there any way to change the "Buyer Info" for example to "Custom Information"? I am reading the docs but i can't seem find something relevant. You can edit Buyer Info form by making changes to this file: tickera\includes\templates\shortcode-cart-contents.php I guess this will get reset when plugin gets updated right? Can i do something so it overwrites it everytime? Yes, you are right. You can overwite it manually after each plugin update, I don't have another idea.
common-pile/stackexchange_filtered
Gedit displays text, but cat tells a different story I am trying to sort a dictionary from Grady Ward's Moby and have encountered a bit of a problem. When I open it in gedit, I get: abaca×N abaciscus×N abacist×N aback×v abacli×p Abaco×N abactinal×A abaculus×N abacus×N abac×N Abadan×N Abaddon×N Abad×N abaft×vP Abagael×N Abagail×N and so on. However, cat mobyposi.i | less tells a different story. I end up getting a mess of characters beginning with <D7> and ending in ^M on every line and it's impossible to read. ^M is definitely a linebreak and dos2unix does not fix this. As far as the <D7>'s go, I'm completely lost. I need to be able to remove both of these to make this human-readable though I'm sure the machine can get through it just fine. :/ I'm running Ubuntu 15.04. I'm getting "unknown 8-bit" That's exactly what I did. I used file -bi my-file.txt and all it told me was that it's an unknown 8-bit file. As we speak I'm searching for solutions, though I've yet to find anything that will format this file the way I wish. Alternatives exist, though some of them don't even include the part of speech! The mobyposi.i file uses old-style Mac line endings, i.e. CR characters. Why? I don't know. This file is from 1993, maybe the author wanted to be Mac-friendly and thought Unix and Windows users could fend on their own. Or maybe the author made a mistake, the readme file states that “the vocabulary file [has] CRLF (ASCII 13/10) delimiters” whereas the delimiters are actually just CR. The words and the part of speech are separated by the byte D7₁₆ = 215₁₀ = 327₈. The × character that Gedit shows is the glyph corresponding to this byte in the Latin-1 encoding. To convert the line endings to Unix line endings (LF) and the word/part separator to :, run LC_CTYPE=C tr '\r\327' '\n:' <mobyposi.i >mobyposi.txt dos2unix didn't do anything because the input didn't have DOS line endings. Gedit automatically detected a file in a foreign encoding (it detected the newlines, and detected a single-byte encoding and picked Latin-1 amongst the many possibilities because it was configured that way). Less doesn't automatically detect foreign encodings, it showed you what the file looks like when interpreted in your locale.
common-pile/stackexchange_filtered
Passing values into a function in MatLab Possible Duplicate: Default Arguments in Matlab I have two functions in Matlab, test1 and test2, as shown below. function [C,D] = test1(A,B) A = 50; B = 20; C = A + B; D = A - B; end and function test2 C = 1000; D = 500; [A,B] = test1(C,D); display(A) display(B) end Now what I would like to do is have set default values for A and B in function test1 but also be able to pass into function test1 different values from another function like function test2. So by default have A and B set to 50 and 20 in function test1, but with function test2 be able to replace them with 1000 and 500, and obtain the equivalent C and D result (in the case of 1000 and 500, get a result of 1500 and 500 for C and D respectively) How can I do this? Any help would be greatly appreciated. Thanks You can use Matlab's varargin for that purpose, e.g. function [C,D] = test1(varargin) A = 50; B = 20; if nargin > 0 A = varargin{1}; end if nargin > 1 B = varargin{2}; end C = A + B; D = A - B; end Several ways to do this Check for the presence of the input: if(~exist('A')) A = default; end Note the use of exist('A') rather than exist(A) - if A doesn't exist by virtue of not being passed, then this will throw an error. Alternatively if(nargin < 2) B = default_b; end if (nargin == 0) A = default_a; end Both of these methods are somewhat messy, and if you have many inputs you want to be optional, then you can use a matlab class inputParser doc inputParser for more details, I don't describe it here because it is very comprehensive (and maybe overkill for simple cases) The exist method was my first thought as well, but then how would you make the function call? I don't think this works unless you evaluate it every time before you call the function. @Dennis `function testfun(testvar, varargin) if(exist('testvar')) disp('moo') end sprintf('%f\n', nargin)` `>> testfun ans = 0.000000 testfun(1) moo ans = 1.000000`
common-pile/stackexchange_filtered
Textmate - render different types of code in different highlighting I have an .html.erb document that has a javascript section at the bottom. Ordinarily Textmate recognizes the <script> tag and converts everything inside to its Javascript(Rails) format. To cut down on <script> tags I enclosed this js code in: # lots of html.erb above... <% content_for :footer_js do %> lots of javascript <% end %> How can I tell Textmate to show the correct highlighting for this Javascript(Rails) section of code? https://gist.github.com/1018085/1049531ca917fa71141dc5e3b7bd7016adaef37d Shows how to do it. You'll just need to change the regex that matches :inline_js to your :footer_js I have also looked for this answer, but after much research, I'm not sure it's possible unless you edit a bundle to add this functionality.
common-pile/stackexchange_filtered
Urllib browerify: Uncaught TypeError: Cannot read property 'split' of undefined I want to use urllib in javascript project (precisely for chrome extension). I need to use some node modules and that includes also urllib. I found out that by using browserify, it is possible to do so. But I got this error after creating the bundle file for urllib. Here is how i tried to include urllib in my project: npm install urllib --save browserify -r urllib -o bundle.js Here is the error I received in bundle.js file: Uncaught TypeError: Cannot read property 'split' of undefined var NODE_MAJOR_VERSION = parseInt(process.versions.node.split('.')[0]); Does anyone know whether it is because urllib is not compatible with browserify or have I overlooked any step? I have the same error but using the "got" module: const nodejsMajorVersion = Number(process.versions.node.split('.')[0]);
common-pile/stackexchange_filtered
plot two matrices both of (4*36 double) size in mat lab I would like to plot two matrices both of (4*36 double) size. The first contains rho and the second contains depths for the 36 locations well I looked into surf but it reads two arrays and one matrix rather than two matrices and yes I would like to plot them as column graph here is an example rho= magic(36); rho(5:1:end,:)=[]; D= magic(36); D(5:1:end,:)=[]; D=sort(depth); So right now the matrix rho contains the densities for the 36 location at four different depths. The matrix D contains the four different depths at which the reading at rho is found. The first element in the first matrix corresponds to the first element in the second matrix and so on in the end what I would like to have is the 36 column with the different reading from (rho) plotted against appropriate depth in (D) I hope I helped make it clearer somehow Have you looked at surf()? Otherwise, it's hard to guess what you want with the info you provided. Consider providing examples, link to examples etc... How do you want to plot them? Four line graphs? Surface plot? Pie chart? As it is you have made a statement and not even asked a question. I realize this is your first question... but ask yourself "can anyone help me with the information I have given"? "Do they know what rho and depth mean to me?" etc... Thanks Floris for the comment I made some changes and I hope that helps Simple example of plotting four sets of X and Y data: X = repmat(1:36, [4 1]); Y(1,:) = rand(1,36); Y(2,:) = 0.2 * (1:36); Y(3,:) = 5 * sin(linspace(-pi,pi,36)); Y(4,:) = 0.1 * (1:36).^2; figure plot(X', Y') This results in Note - in order to get four series to plot like this, the data has to be in COLUMNS. The original data was in 4x36 matrix, so it was in ROWS. I used the transpose operator (apostrophe - X' rather than just X) to get the data organized in columns. Maybe this helps...
common-pile/stackexchange_filtered
Max user connection error. When I uploaded my site online. but it works in localhost This is my config.php code This works when I am on localhost but when I uploaded the site it does not work anymore. I tried searching here for answer but being a newbie makes my life hard. <?php define("DB_HOST", "mysql.hostinger.ph"); define("DB_USER", "myuser"); define("DB_PASS", "mypassword"); define("DB_NAME", "mydbname");?> And this is my Database.php code <?php $filepath = realpath(dirname(__FILE__)); include_once($filepath.'/../config/config.php'); ?> <?php Class Database{ public $host = DB_HOST; public $user = DB_USER; public $pass = DB_PASS; public $dbname = DB_NAME; public $link; public $error; public function __construct(){ $this->connectDB(); } private function connectDB(){ $this->link = new mysqli($this->host, $this->user, $this->pass, $this->dbname); if(!$this->link){ $this->error ="Connection fail".$this->link->connect_error; return false; } } // Select or Read data public function select($query){ $result = $this->link->query($query) or die($this->link->error.__LINE__); if($result->num_rows > 0){ return $result; } else { return false; } } // Insert data public function insert($query){ $insert_row = $this->link->query($query) or die($this->link->error.__LINE__); if($insert_row){ return $insert_row; } else { return false; } } // Update data public function update($query){ $update_row = $this->link->query($query) or die($this->link->error.__LINE__); if($update_row){ return $update_row; } else { return false; } } // Delete data public function delete($query){ $delete_row = $this->link->query($query) or die($this->link->error.__LINE__); if($delete_row){ return $delete_row; } else { return false; } } } Then I get max user connection on Database.php line 22. I tried my best to search for a solution I hope that you can help my newbie mind ahhahah. The most easiest reliable way is to contact your hosting provider. Most of the time, max user connection errors is solved this way. Because usually you are not allowed (privileged) to execute useful queries to solve it(like Grant usage...) or change required configurations under a shared hosting environment. But after all, it could be useful to read about it: https://dba.stackexchange.com/questions/47131/how-to-get-rid-of-maximum-user-connections-error proper way to solve mysql max user connection error How to solve MySQL max_user_connections error @Galvezo.A Hope it helps I think the problem is not in your code,possible in the mysql server.There are options in mysql config file,like this: myisam-recover-options = BACKUP max_connections = 100 #table_cache = 64 #thread_concurrency = 10 The problem maybe is the max_connections,which means this will allow 100 connections to the server at most. If you are use third-party mysql server,this problem may happen... Thanks for answering sir. Do you have any tips on how to fix this? contact the mysql server provider Thanks sir for tip I will try my best haha hopes this works.
common-pile/stackexchange_filtered
Php/jquery: How to show value of array loaded elements from db with a loop? I've written the following php code: $query = mysql_query("SELECT * FROM utenti WHERE username = '$username'"); $query_db = mysql_query("SELECT * FROM utenti"); $i = 0; $array_user = mysql_fetch_array($query); $dati = array("str"=>array()); while ($array_db = mysql_fetch_array ($query_db)) { if ($array_user[country] == $array_db[country]) { if ($array_user[city] == $array_db[city]) { if ($array_user[cap] == $array_db[cap]) { if ($array_user[square] == $array_db[square]) { $dati["str"]["n".$i] = "Nome ".$array_db[username]; $i++; } } } } } echo json_encode ($dati); I want to load an array using elements from database during a loop: $dati["str"]["n".$i] = "Nome ".$array_db[username]; and then to show index and value of this array after an Ajax request: ... success:function(msg){ if(msg){ $.each(msg.str, function(key, value){ console.log(key + ": " + value); }); }else{ $("#location").html('Not Available'); } It doesn't work and I can't find the mistake. Could you help me, please? What is there in a console? Any errors? No any errors. It's empty. @u_mulder ANd console.log(msg.str)? There's written: Object {n0: "Nome fabio97", n1: "Nome antonino", n2: "Nome Marcuccio", n3: "Nome silvia"} @u_mulder And your $.each is not logging anything? No now It works but if I write: $("#location").html(key + ": " + value); it shows only the last element n3: Nome silvia and not everyone. Why? How can I fix? @u_mulder Supposing your code $.each(msg.str, function(key, value){ console.log(key + ": " + value); }); works fine. Then, your attempt $("#location").html(key + ": " + value); means that everytime contents of #location will be overwritten. Instead, you can use append(): $.each(msg.str, function(key, value){ console.log(key + ": " + value); $("#location").append(key + ": " + value); }); Thanks, I write: $("#location").html((Object.keys(msg.str).map(x => msg.str[x]).join("<br />"))); and it works. What the differences between this instruction and the one with append? @u_mulder append() appends data to div on each iteration. And your code implodes (joins) all data from object and put it in a div once.
common-pile/stackexchange_filtered
Please explain me with one example for : DATEADD(MONTH,DATEDIFF(MONTH,0,GETDATE())-6,0) Hello i reviewed this article.But i can not understand how it works? DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) Can someone explain me this Please explain me with one example for : DATEADD(MONTH,DATEDIFF(MONTH,0,GETDATE())-6,0) You've linked to an existing question, and that question has multiple answers. If the answers are unsatisfactory, please highlight why. Don't just demand new answers. Possible duplicate of DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) Can someone explain me this why you guys do not understand that i already mentioned that this question is similar to that question but i did not understand clearly so i am asking it again.and you guys just gave me minus marking.so frustrated. Because you've not explained why the existing answers are unsatisfactory. We don't know that, and you've not explained. those answer did not understand by me.You can also see that there is a difference between my question and above question.So i am confused. The DATEADD() function adds or subtracts a specified time interval from a date. DATEADD(datepart,number,date) The DATEPART() function is used to return a single part of a date/time, such as year, month, day, hour, minute, etc. DATEPART(datepart,date) The DATEDIFF() function returns the time between two dates. DATEDIFF(datepart,startdate,enddate) datepart can be d-> day m-> month y-> year your query can be split as below:- select GETDATE() --> returns Current date eg: 2016-01-12 01:07:35.453 select DATEDIFF(MONTH,0,GETDATE()) --> returns months between two dates, 0 is for 1/1/1900 ->1392 i.e you can re write it as: select DATEDIFF(MONTH,1/1/1900,GETDATE()) next:- select DATEDIFF(MONTH,0,GETDATE())-6 --> substract 6 months again -> 1386 re-writing:- select DATEDIFF(MONTH,1/1/1900,GETDATE())-6 then:- select DATEADD(MONTH,DATEDIFF(MONTH,0,GETDATE())-6,0) -->add 1386 months to '1/1/1900' re-writing as:- select DATEADD(MONTH,DATEDIFF(MONTH,1/1/1900,GETDATE())-6,1/1/1900) in short your quwey is equivalent to select DATEADD(MONTH,1386,1/1/1900) This part: SELECT DATEDIFF(MONTH,0,GETDATE()) Selecting number of month after 1900-01-01 so current month is 1392 And with SELECT DATEADD(MONTH,1392-6,0) you substracting 6 months from current month. So you got output: 2015-07-01 00:00:00.000 This closely parallels the highest voted answer on the existing question the OP links to. If this answer "works" for the OP then it means the question should definitely be closed as a duplicate.
common-pile/stackexchange_filtered
VS Code Java SDK Creates Project Errors on Default Components (Main Method, Double, String etc.) Environment: I had a series of unexplainable errors on a macOS system running macOS Big Sur and while I was trying to run my application using this guide from the official VS Code website. Issue: Every time I opened a certainly working project in VS Code (tested in the IntelliJ IDE), it was full of errors like String is not a known class or main method not defined in class etc. Understanding the Problem: I quickly figured out that the issue has to do with the JDK being misconfigured, and now I had to figure out if the issue was in VS Code or Homebrew. The issue I suspected lied in VS Code and originated from my choice to use a JDK downloaded and managed by the Homebrew package manager. After verifying my Homebrew installation of the given cask and making sure system paths were set correctly, I was certain of the previously made assumption. Solution: Open the folder in VS Code Collapse the Java Projects Tab in the Explorer menu (make sure you have the [java language package extension][3] downloaded) Click the three dots icon '...' which appears when you hover over the Java Projects area with your mouse. Select 'Configure Java Runtime'. A new tab will open. On the Java Version column, select the pencil icon. Open the dropdown menu and select a Java Version from the Java Virtual Machines folder instead of opt/Homebrew directories (it may be the same JDK from Homebrew using an alias, but VS Code expects the Virtual Machine folder and that is my theory in why this works). You may accept your answer to mark this question as resolved. I will, it's just that it requires 4 more hours to do so according to the 2-day waiting period on Stack Overflow.
common-pile/stackexchange_filtered
How to show the total values of rows in a Matrix with number value having my columns values as percentage I've started to manage PowerBi from a couple of weeks so i'm a little bit confused about some things. My problem is that i need a Matrix in my dashboard with percent values but i want the total in number value because the total of a percent of row shows me always 100% and i dont know about the number i'm working This is my Matrix with percentage values This is how i want the total of row returns me but with the columns values ins percentage I've tried to make a measure counting the values COUNT(OPSRespuestas[answer]) After that turn off the total of rows and add this measure to the values in my matrix but this is what i get This is my table after trying add a measure with the total It returns me the total for each of the columns and not the total of all my rows. These are the tables i'm working with This my top header values This is my left header values The answer column is what i need to count This is my relationship between this 3 tables although i have many more intermediate table aside from this 3 as you're going to see in the next picture: My relationship tables So finally what i need is that this matrix shows me the total of answer in percentage for each of departments and group of questions and then show me total by department but with number value Turn off "Total". Instead, write a DAX measure that calculates whatever you need for the total. Add the measure to the matrix. I've just tried what you told me and i made i measure, i turned off the subtotal of rows and i added my measure to values in the Matrix but it returns me the Total for each of the columns The problem you are experiencing has to do with context. Each row is seen as it own total population hence the 100% total. Each column in this row is evaluated against the total of that row to provide a percentage value. In addition to adding a custom measure to replace the total, you could also consider computing a percentage against the grand total of all dimensions. This means that each cell gets evaluated against the the total of all rows and columns. In this ways the cell value would change compared to your first table but the row total does not evaluate to 100% anymore. SUM ( [Value] ) / CALCULATE ( SUM ( [Value] ) ; ALL ( 'Your Table' ) ) Where i should add that measure?? because i'm doing it over values in the matrix and it doesn't work Should do the trick in the values box but I didn't know you were using a count. This should work better COUNTA( 'Your table'[Value] ) / CALCULATE( COUNTA( 'Your table'[Value] ) ; ALL( 'Your table' ) ) i dont know the reason but i tried this with my answers table and it results me 0 in each row. Can you share a picture of your model so I can have a look at your relationships? It probably requires a little refinement considering you are using multiple tables to generate the matrix, is that correct? Yes i'm using 3 tables for this exercise i share the relationship. Thank you! Thanks for sharing, looks like a rather complex model. Are you using any of the inactive relationships in certain calculations? Is this the measure you made from my pseudo code: COUNTA ( 'OPSRespuestas'[Answer] ) / CALCULATE ( COUNTA ( 'OPSRespuestas'[Answer] ) ; ALL ( 'OPSRespuestas' ) ) ? Yes i've just done that measure and it doesnt work. I'm just using the 3 tables i marked Hmmm, something else must be going on then because I do get the desired result in a assumed simulation of your above model. What happens if you both both the count and the percentage measure in the same table? Although you are explicitly using only 3 tables you implicitly use the tables that link them up through their relationships as well. Probably the cause of your problem is somewhere in there.
common-pile/stackexchange_filtered
Convert std::filebuf(FILE*) to use libc++ I have some existing code that I am trying to compile using clang 3.3 and libc++ from llvm.org. A simple step to retrieve the result of another command. It appears that std::filebuf doesn't offer a FILE* constructor any more and all the ideas that I have tried to replace the code have all failed to open the command, that is fb.is_open() always returns false. From what I can find I would have to use something like fb.open(cppcommand.c_str(), std::ios::in); instead of popen. The essential parts of the code are :- std::string cppcommand = "/usr/bin/cpp -xc -nostdinc test.c"; FILE *cpppipe = popen (cppcommand.c_str(), "r"); std::filebuf fb (cpppipe); if (! cpppipe || ! fb.is_open()) { std::cerr << "Could not run '" << cppcommand.c_str() << "'\n"; return false; } else { std::istream in (&fb); std::ostringstream ss; ss << in.rdbuf(); result = ss.str(); } How can I get this running with libc++? The code is from OpenShadingLanguage and I am trying to get it to compile under FreeBSD 10.0 Beta1 which contains clang 3.3 and libc++ after removing gcc and libstdc++ from the base install. The cppcommand string being used runs without error if manually pasted into the terminal. Actually std::filebuf has never offered a constructor taking a FILE*. You've fallen victim to a gcc extension. The C++ I/O system is very extensible, though in a fairly antique fashion. It is not that difficult to create a custom streambuf which could be constructed from a FILE*, in perfectly portable C++. Normally I'd just plop the code down here. However it is a little long for an answer. And normally I don't shamelessly plug a product instead of offering an answer. In this case I'm making an exception. Josuttis' "The C++ Standard Library" shows how to do this for a POSIX file descriptor in section 15.13.3. It would be trivial to adopt this code to use a FILE* instead of a POSIX file descriptor. If this was the only thing you could get out of Nicolai's book, I probably wouldn't recommend it. However that is far from the case. I recommend this book.
common-pile/stackexchange_filtered
blocking phone number in call kit I'm trying to using CallKit to add a feature to my app to add some phone numbers to blacklist! the code below is my whole view!! class BlacklistViewController: UIViewController ,UITableViewDataSource, UITableViewDelegate { var phoneNumbersArrCoreData = [BlockedPhoneNumbers]() var listPhoneNumbers:[CXCallDirectoryPhoneNumber] = [] @IBOutlet weak var TableView: UITableView! @IBOutlet weak var BtnAddO: UIButton! @IBOutlet weak var EntPhonenumber: UITextField! @IBAction func BtnAddA(_ sender: Any) { if !(EntPhonenumber.text?.isEmpty)! { let blackedPhonenumbers_CoreData = BlockedPhoneNumbers(context: PersistanceService.context) blackedPhonenumbers_CoreData.phoneNumber = Int64.init(EntPhonenumber.text!)! PersistanceService.saveContext() getCoreData() TableView.reloadData() } } var coreData = [BlockedPhoneNumbers]() func getCoreData() { listPhoneNumbers.removeAll() let fetchRequest : NSFetchRequest<BlockedPhoneNumbers> = BlockedPhoneNumbers.fetchRequest() do { let FetchedResultFromDB = try PersistanceService.context.fetch(fetchRequest) coreData = FetchedResultFromDB print("============\n===========\n") if coreData.count > 0 { for i in 0..<coreData.count { listPhoneNumbers.append(coreData[i].phoneNumber) } } print("============\n===========\n") } catch{ print("gettin blocked number from db got error") } } override func viewDidLoad() { BtnAddO.layer.cornerRadius = 5 BtnAddO.layer.borderColor = UIColor.white.cgColor BtnAddO.layer.borderWidth = 0.8 EntPhonenumber.attributedPlaceholder = NSAttributedString(string: "Enter a phone number to block",attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightText]) getCoreData() super.viewDidLoad() view.backgroundColor = UIColor.init(red: 25/255, green: 28/255, blue: 46/255, alpha: 1) TableView.delegate = self TableView.dataSource = self } func beginRequest(with context: CXCallDirectoryExtensionContext) { getCoreData() let blockedPhoneNumbers: [CXCallDirectoryPhoneNumber] = listPhoneNumbers for phoneNumber in blockedPhoneNumbers.sorted(by: <) { context.addBlockingEntry(withNextSequentialPhoneNumber: phoneNumber) } context.completeRequest() } //MARK: - TableView func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return listPhoneNumbers.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "BlackListCell") as? BlackListTableViewCell cell?.ContactImg.layer.masksToBounds = true cell?.mainView.layer.cornerRadius = 10 cell?.mainView.backgroundColor = UIColor(red: 42/255, green: 48/255, blue: 66/255, alpha: 1) cell?.ContactImg.layer.cornerRadius = 5 cell?.ContactImg.image = UIImage(named: "Blocked") cell?.unBlock.imageView?.image = nil cell?.unBlock.setTitle("UNBLOCK", for: UIControl.State.normal) cell?.unBlock.layer.cornerRadius = (cell?.unBlock.frame.size.height)!/2 cell?.SetUnblockBtn { I get the error here,below let context:NSManagedObjectContext = PersistanceService.context context.delete(self.phoneNumbersArrCoreData[indexPath.row] as NSManagedObject) self.phoneNumbersArrCoreData.remove(at: indexPath.row) print("data deleted!!!") } cell?.phoneNumber.text = String(listPhoneNumbers[indexPath.row]) return cell! } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 85 } } to explain the code, I save each number that user will enter in a core data(entityName: BlockedPhoneNumbers). I'm not sure even if this is the right way to save numbers that they need to be blocked or not!! when the user presses the button I save the number and it works fine( but I'm not sure if this is the right way or not!!). and in getCoreData I get the core data and show them in a table view. which shows that core data works fine! but when user wanna unblock the contact and presses the button in CELL of the table view, I get an error and app crash and it says: Thread 1: Fatal error: Index out of range my problems are: why do I get this error? 2.as I can not find any tutorial for callKit I believe that I'm doing this job wrong. could anyone help me with this? Which line of code exactly is causing the error? context.delete(self.phoneNumbersArrCoreData[indexPath.row] as NSManagedObject) Make that clear in your question, not in comments. check the code again pls I changed it The indexPath is based on listPhoneNumbers, not phoneNumbersArrCoreData. the data as I'm showing in the table view is coming from listPhoneNumbers, but to delete the core data record I have to access phoneNumbersArrCoreData! do you have any solution ?? these two arrays have a different type You need to put the beginRequest(with context: CXCallDirectoryExtensionContext) in a call kit directory extension. You should get rid of listPhoneNumbers and just drive your table view from phoneNumbersArrCoreData then how should I add a phone number to blacklist if I move the begin request to extension!!!!?? Actually, I have already added the call kit extension but I have no Idea how to access it to store the phone numbers! You need to use an application group to share your Core Data repository between your app and the extension You have too many arrays: listPhoneNumbers which contains your integer numbers coreData which contains your Core Data items phoneNumbersArrCoreData which could contain your Core Data items, but you don't add anything to it. As a result, phoneNumbersArrCoreData is empty. When you try and remove an object from the empty array you get an array bounds exception. You should eliminate two of the three arrays. class BlacklistViewController: UIViewController ,UITableViewDataSource, UITableViewDelegate { var blockedNumbers = [BlockedPhoneNumbers]() @IBOutlet weak var TableView: UITableView! @IBOutlet weak var BtnAddO: UIButton! @IBOutlet weak var EntPhonenumber: UITextField! @IBAction func BtnAddA(_ sender: Any) { if !(EntPhonenumber.text?.isEmpty)! { let blackedPhonenumbers_CoreData = BlockedPhoneNumbers(context: PersistanceService.context) blackedPhonenumbers_CoreData.phoneNumber = Int64.init(EntPhonenumber.text!)! PersistanceService.saveContext() getCoreData() TableView.reloadData() } } func getCoreData() { let fetchRequest : NSFetchRequest<BlockedPhoneNumbers> = BlockedPhoneNumbers.fetchRequest() do { let FetchedResultFromDB = try PersistanceService.context.fetch(fetchRequest) blockedNumbers = FetchedResultFromDB print("============\n===========\n") } catch{ print("gettin blocked number from db got error") } } override func viewDidLoad() { BtnAddO.layer.cornerRadius = 5 BtnAddO.layer.borderColor = UIColor.white.cgColor BtnAddO.layer.borderWidth = 0.8 EntPhonenumber.attributedPlaceholder = NSAttributedString(string: "Enter a phone number to block",attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightText]) getCoreData() super.viewDidLoad() view.backgroundColor = UIColor.init(red: 25/255, green: 28/255, blue: 46/255, alpha: 1) TableView.delegate = self TableView.dataSource = self } //MARK: - TableView func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return blockedNumbers.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "BlackListCell") as? BlackListTableViewCell cell?.ContactImg.layer.masksToBounds = true cell?.mainView.layer.cornerRadius = 10 cell?.mainView.backgroundColor = UIColor(red: 42/255, green: 48/255, blue: 66/255, alpha: 1) cell?.ContactImg.layer.cornerRadius = 5 cell?.ContactImg.image = UIImage(named: "Blocked") cell?.unBlock.imageView?.image = nil cell?.unBlock.setTitle("UNBLOCK", for: UIControl.State.normal) cell?.unBlock.layer.cornerRadius = (cell?.unBlock.frame.size.height)!/2 cell?.SetUnblockBtn { let context:NSManagedObjectContext = PersistanceService.context context.delete(self.blockedNumbers[indexPath.row] as NSManagedObject) self.phoneNumbersArrCoreData.remove(at: indexPath.row) print("data deleted!!!") } cell?.phoneNumber.text = blockedNumbers[indexPath.row].phoneNumber return cell! } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 85 } } The code to actually load data into the Call Kit block list needs to go into a CallKit extension in your app. You will need to use an application group to share the Core Data store with the extension. You will need to use an application group to share the Core Data store with the extension. could guide me pls with this part! https://medium.com/@maximbilan/ios-shared-coredata-storage-for-app-groups-447b4ba43eec and as you mentioned the arrays, i fixed that. as you mentioned both phoneNumbersArrCoreData and CoreData are the same , so, I deleted the phoneNumbersArrCoreData I didn't get point of using the application group!! in this linked the person has connected the Apple watch and today's extension! They have connected their main app with a today extension and a watch app using an application group. In your case your main app and your call kit extension need to use the same application group so now I need to connect the core data with call extension like the link you provided! is that right? Yes. They need to share a Core Data store. You will also need your main app to refresh your call kit extension when the data changes. refresh your call kit extension when the data changes !!! what does this mean! :| You need to call CXCallDirectoryManager.sharedInstance.reloadExtension(withIdentifier: completionHandler:) I did everything as you said, connected my core data to extension and in my VC I reloadedExstension and I get an error which says: Error Domain=com.apple.CallKit.error.calldirectorymanager Code=0 "(null)" The operation couldn’t be completed. (com.apple.CallKit.error.calldirectorymanager error 0.). and as I searched the net this error is unknown in call kit API. have you ever faced it or do u have any idea You should ask another question, giving details of the error and showing the relevant code. https://stackoverflow.com/questions/53698494/blocking-phone-numbers-in-call-kit-has-couple-of-errors?r=SearchResults . please check this new question
common-pile/stackexchange_filtered
Approximating dense subspaces of Fréchet spaces If $H$, $H_0$ are two separable Hilbert spaces and $H$ is continuously and densly embedded in $H_0$, it is possible to construct a sequence of linear operators $$ P_n : H_0 \to H $$ such that for all $x \in H_0$ one has convergence $P_n x \to x$ in the $H_0$-norm. The motivation is to generalize the idea of smoothing operators. For example, $H^2(\mathbb R)$ is densely embedded in $L^2(\mathbb R)$ and it is well known that one can approximate each $L^2$-function by an $H^2$-function. In this case $P_n$ could be a convolution with a smooth kernel with width $1/n$. Can this be generalized to Fréchet spaces or even beyond? If $H$ and $H_0$ are Fréchet spaces rather than Hilbert spaces, is it always possible to construct a sequence of bounded operators $P_n$ as above? In the Hilbert case one way to construct $P_n$ is by considering an unbounded, self-adjoint operator $A : D(A) \to H_0$, with $D(A)=H$, that represents the inner product via $$ \langle v,w \rangle_H = \langle Av, Aw \rangle_{H_0}\,. $$ If $\{ P_\Omega\}$ is the spectral measure accociated to $A$, then we can use $P_{[-n,n]}$ as our sequence of operators. It is less clear to me, what to with Fréchet spaces. Suppose the embedding of $H$ into $H_0$ is compact. Then you are asking for the identity to be a strong limit of compact operators. I believe this is called the "compact approximation property" and there are Banach spaces that don't have it. Hopefully an expert can fill in the details or give references. Yes, I think you are right. It also fits with the answer given below: if we assume that our space has a Schauder basis, then it has the approximation property. A Banach or Frechet space $H_0$ is separable and has the BOUNDED approximation property (BAP) iff there is a sequence $P_n$ of continuous finite rank operators on $H_0$ that converges strongly to the identity. A simple perturbation argument show that you can take these operators to range in any dense subspace you want. On the other hand, if $H_0$ fails the analogous compact bounded approximation property and the inclusion from $H$ into $H_0$ is compact, then, as Nate pointed out, you cannot get a sequence that has the property you want. What else are you looking for? Thank you, now I am quite happy. I realized how to remove the requirement that the space admits a continuous norm and posted a writeup below. Here is a very simple method for separable Hilbert spaces (which easily generalizes to Frechet spaces with Schauder bases): Take an orthonormal basis $(e_k)_k$ in $H_0$ and choose $f_{n,k}\in H_1$ such that $\|e_k-f_{n,k}\|_0 \le 1/(n^2+k^2)$. Then define $P_n(x)=\sum_{k=1}^n \langle e_k,x\rangle_0 f_{n,k}$. The difference $\|P_n(x)-x\|_0$ is estimated just using the triangle inequality (so that this construction isn't bound to Hilbert spaces). EDIT. I add some details for the Frechet case showing (at least under a mild additional assumption) that one does not need an absolute basis (which would exclude many Banach spaces, I recall the definitions below). Let $(\|\cdot\|_N)_{N\in\mathbb N}$ be an increasing sequence of seminorms giving the topology of the Frechet space $H_0$. A Schauder basis $(e_k)_k$ is a sequence such that that every $x\in H_0$ has a unique representation $x=\sum\limits_{k=1}^\infty \xi_k(x)e_k$. (The basis is called absolute if, for each $N$, there are $M$ and $c>0$ such that $\sum\limits_{k=1}^\infty |\xi_k(x)|\|e_k\|_N \le c\|x\|_M$ for all $x\in H_0$ -- this implies that the spaces is a projective limit of weighted $\ell^1$ spaces and excludes Hilbert spaces). By corollary 28.11 in the book Introduction to Functional Analysis of Meise and Vogt one has a slightly weaker condition for every Schauder basis: For every $N$ there are $M=M(N)$ and $c>0$ such that $\sup\lbrace|\xi_k(x)|\|e_k\|_N:k\in\mathbb N\rbrace \le c\|x\|_M$. In particular, the coefficient functionals $\xi_k$ (which are linear by the uniqueness) are continuous. We construct $P_n$ under the additional assumptions that $\|\cdot\|_1$ is a norm and not only a seminorm (I am quite optimistic that this can be removed). For $n,k \in\mathbb N$ choose $f_{n,k}\in H_1$ with $\|e_k-f_{n,k}\|_n\le \|e_k\|_1/n^2$ and set, as previously, $P_n(x)=\sum\limits_{k=1}^n\xi_k(x)f_{n,k}$. These are continuous linear operators $H_0\to H_1$, and for each $x\in H_0$, $N\in\mathbb N$, and $n\ge N$ we have $$ \|P_n(x)-x\|_N \le \sum_{k=1}^n |\xi_k(x)|\|f_{n,k}-e_k\|_N + \|\sum_{k=n+1}^\infty\xi_k(x)e_k\|_N. $$ The second term tends to $0$ and (since $n\ge N$) the first term can be estimated by $\sum_{k=1}^n |\xi_k(x)|\|e_k\|_1/n^2 \le c\|x\|_{M(1)}/n$. Thank you, this is very helpful. When generalizing the construction to Fréchet spaces, I seem to require an absolute basis, in order to control the terms $\langle u_k, x \rangle$ in the sum; here $u_k \in H_0^\ast$ are the coordinate functionals of the basis $(e_k)_k$. Another remark. Uniqueness of the basis representation is not need and one can argue with atomic decompositions instead. The article https://arxiv.org/abs/1212.0969 of Bonet, Galbis, Fernandez, and Ribera contains some information about that. Corollary 1.5 of the mentioned article says that a Frechet space has an atomic decomposition if and only if it has the bounded approximation property. This fits very well with Nate's comment above. I tried to remove the requirement that $|\cdot|_1$ is a norm, both in your construction and in Matthew's construction below, but I was not able to do this. One has to estimate things with norms $| \cdot|_n$ with $n$ higher and higher and looses too much control in the process. In any case this has been very helpful! Thanks to Jochen, Matthew and Bill, this is a detailed proof for Fréchet spaces. Proposition. Let $E$ be a separable Fréchet space with the bounded approximation property, $F$ a topological vector space, continuously and densely embedded in $E$. Then there exists a sequence of continuous linear maps $P_n : E \to F$, such that $$ \forall x \in E\,:\, P_n x \to x \text{ in }E\,. $$ Proof. Let $(x_n)_{n \in \mathbb N}$ be a countable, dense sequence in $E$ and $(\|\cdot\|_n)_{n \in \mathbb N}$ an increasing fundamental system of seminorms. We assumed that $E$ has the bounded approximation property, hence there exists an equicontinuous sequence of linear maps $T_n : E \to E$ with finite rank that converge to $\operatorname{Id}_E$, uniformly on compact sets. By passing to a subsequence we can assume that $$ \| T_n x_j - x_j \|_n \leq \frac 1n \text{ for }j \leq n\,. $$ Due to equicontinuity there exists for each $m$, an $N_m \in \mathbb N$ and $C_m>0$ such that $$ \forall n \in \mathbb N\,,\; \forall x \in E\,:\, \| T_n x \|_m \leq C_m \| x \|_{N_m}\,. $$ For each $n$, the space $T_n(E)$ is finite dimensional. Let $n'=n'(n)$ be such that $\|\cdot\|_{n'}$ is a norm on $T_n(E)$. We can construct a map $S_n : T_n(E) \to F$ with $$ \| S_ny - y \|_{n} \leq \frac 1n \| y \|_{n'}\,, $$ for all $y \in T_n(E)$. To see that this is possible choose a basis $y_1, \dots, y_m$ of $T_n(E)$ and note that it is sufficient to define $S_n(y_i) \in F$, such that $\| S_n(y_i) - y_i \|_{n}$ is small enough. This is possible, because $F$ is dense in $E$. Define $P_n = S_n T_n$. We have to show convergence $P_n x \to x$. Fix $x \in E$ and a seminorm $\|\cdot\|_m$. For $n$ and $k$ satisfying $m ,\,N_m,\,N_{m'} \leq n$ and $k \leq n$ we have \begin{align*} \| P_n x &- x \|_m \leq \|S_n T_n(x-x_k) -T_n(x-x_k) \|_m + \| T_n(x-x_k) \|_m + \\ &\qquad\qquad\qquad + \|S_n T_n x_k - T_n x_k \|_m +\| T_n x_k - x_k\|_m + \| x_k - x\|_m \\ &\leq \frac 1n \| T_n(x-x_k) \|_{m'} + C_m \| x - x_k \|_{N_m} + \frac 1n \| T_n x_k \|_{m'} + \frac 1n + \|x_k - x \|_m \\ &\leq \frac {C_{m'}}{n} \| x-x_k \|_{N_{m'}} + C_m \| x - x_k \|_{N_m} + \frac {C_{m'}}n \left( \| x\|_{N_{m'}} + \| x-x_k \|_{N_{m'}} \right) + \\ &\qquad\qquad + \frac 1n + \|x_k - x \|_m \,. \end{align*} We see that by choosing $n$ large enough and $\|x - x_k\|_n$ small enough we can achieve convergence. Edit: So I think my real mistake was in the claim that "if $H_0$ is separable then we can use a sequence". As Bill Johnson implictly points out, you can always find a net $P_\alpha:H_0\rightarrow H$. Just to correct the argument (though Martins now gives it in more generality)... If $H_0$ has the bounded approximation property, then there is an absolute constant $\lambda>0$ so that for $x_1,\cdots,x_n\in H_0$ there is a finite-rank operator $T:H_0\rightarrow H_0$ with $\|T\|\leq \lambda$ and $\|T(x_i)-x_i\| \leq \epsilon$ for each $i$. In our case, $\iota:H\rightarrow H_0$ is a continuous map with dense range. For $x_1,\cdots,x_n \in H_0$ and $\epsilon>0$ we find a finite-rank $T$ with $\|T\|\leq\lambda$ and $\|T(x_i)-x_i\| \leq \epsilon$ for each $i$. As $T(H_0)$ is finite dimensional and $\iota$ has dense range, we can find a linear map $S: T(H_0) \rightarrow H$ so that that $\|\iota S(x) - x\| \leq \epsilon$ for all $x$ in the unit ball of $T(H_0)$. [Proof: If $M\subseteq H_0$ is finite-dimensional, with linear basis $m_1,\cdots,m_n$, then as all norms are equivalent on $M$, if we can ensure that $\|\iota S(m_i)-m_i\|$ is very small, then $\|\iota S(x)-x\|$ will be small uniformly on the unit ball of $M$. But this follows as $\iota$ has dense range and we can choose each $S(m_i)$ completely freely.] Then $\| \iota ST(x_i) - x_i\| \leq \| \iota ST(x_i) - T(x_i) \| + \| T(x_i) - x_i \| \leq \epsilon \|T(x_i)\| + \epsilon$ $\leq \epsilon^2 + \epsilon\|x_i\| + \epsilon$. So $ST : H_0 \rightarrow H$ approximates the identity in the $H_0$ norm. If we want a net, we just let $(x_i)_{i=1}^n$ run through all finite subsets of $H_0$, and observe that we didn't use the bound on $T$, so as Bill Johnson suggests, we could just take $T$ to be a projection onto the span of the $(x_i)$, no condition on $H_0$ needed. If $H_0$ is separable, let $(x_k)$ be a countable dense subset, and let $S_nT_n$ be chosen as above for $(x_i)_{i=1}^n$ and $\epsilon=1/n$. If $x\in H_0$ with $\|x - x_i\| \leq \epsilon$ for some $i\leq n$, then \begin{align*} & \| \iota S_nT_n(x) - x \| \leq \| \iota S_nT_n(x) - x \| \\ & = \| \iota S_nT_n(x-x_i) - T_n(x-x_i) + \iota S_n T_n(x_i) - T_n(x_i) + T_n(x) - x \| \\ &\leq \epsilon\|T_n(x-x_i)\| + \epsilon\|T_n(x_i)\| + \|T_n(x-x_i) - (x-x_i) + T_n(x_i) - x_i \| \\ &\leq \epsilon^2\lambda + \epsilon(\epsilon+\|x_i\|) + \epsilon\lambda + \epsilon \\ &\leq \epsilon^2\lambda + \epsilon(2\epsilon+\|x\|) + \epsilon\lambda + \epsilon. \end{align*} Without the BAP you seemingly cannot control $\|T(x-x_i)\|$ for example. Remark 1: Having the "compact approximation property" doesn't seem to help. By definition, this means we can only choose $T$ to be compact not finite-rank. Then the image of the unit ball of $H_0$ under $T$ is a compact set, but I don't know how to form the equivalent of $S$. That is, how do you (linearly) distort a compact set from $H$ into $H_0$? Thank you for the answer. I checked the details for Fréchet spaces. I can generalize your argument to show that if $H_0$ has the bounded approximation property and admits a continuous norm, then one can construct the sequence of operators $P_n$. In that case the family $(P_n)$ is also equicontinuous. This fits nicely with Jochen's comment, that existence of atomic decompositions is equivalent to the bounded approximation property. @MatthewDaws: That is not the definition of the AP. Moreover, if $E$ is a finite dimensional subspace of a locally convex space $X$, then there is a continuous projection from $X$ onto $E$.
common-pile/stackexchange_filtered
How to use images in Keyboard Extension? Kindly Someone Help me, I want to develop my custom keyboard in objective-c. I am not find a way to use images in keyboard extension.Basically I want to show images on Keyboard and after click on image I want to paste on board. Kindly please help me share a way and tutorial link of keyboard extension in objective C with images. similar to this link: How to create custom keyboard extension with images on it in Objective-C? I need proper steps to how use image on extension keyboard and how to share this image Please kindly read this: http://stackoverflow.com/help/how-to-ask
common-pile/stackexchange_filtered
Flutter: issue with Future which block a function I am currently developping a flutter application with Dart. I want to add some local notification when there is something new. For that I'm using a periodic task with workmanager, which make a http request to check the last "news". The issue here is that the function stop at client.get() Future<List<String>> _grepLastNews() async { var client2 = new http.Client(); debugPrint("here"); //issue below final response = await client2.get('http://..../lireLastNews.php').timeout(Duration(seconds: 4)); client2.close(); debugPrint("here 2"); var body; if (response.statusCode == 200) { body = jsonDecode(response.body); } else { return ["0","0"]; } return jsonDecode(body); } Here you can find the output: output You can see it stop before the second checkpoint... I have tried with and without timeout, with changing the name of the other http client of the application but nothing work. I must add that I have an other http client which work perfectly ( but not in background ^^). Thanks for helping me EDIT: I tried with await Future.delayed(Duration(seconds: 2),() => ["0","0"]); but the output is the same so the issue is not with http.get but about the future which I don't know why stop there. EDIT 2: In fact in an async function I tried debugPrint("here 2"); await Future.delayed(Duration(seconds: 2)); debugPrint("here 3"); and it never go for "here 3". EDIT 3: I tried differents variant using Future.wait([_grepLastNews()]); but it don't work: it continue until raising an error because of the null result of _grepLastNews(). try to wrap your async api call into a try...catch block. that should give you more insights on the issue. Add the error to your question, if you need further help. https://dart.dev/codelabs/async-await I tried with try{ response =await client2.get(...); } catch(e) {debugPrint(e);} but the output is the same as previously.
common-pile/stackexchange_filtered
Java keyPressed() method only works after player presses tab I am making a little game applet, and I have gotten to where the player should move around with the controls. Main: public class Main extends JApplet implements Runnable, KeyListener { private static final long serialVersionUID = 1L; private static DoubleBufferedCanvas canvas = new DoubleBufferedCanvas(); public static int width = 900; public static int height = 600; public static int fps = 60; public static Ailoid ailoid = new Ailoid(); public static Player player = new Player(); // Initialize public void init() { setSize(width, height); setBackground(Color.white); add(canvas); addKeyListener(this); setFocusable(true); setFocusTraversalKeysEnabled(false); ailoid.setLocation(new Location(100, 100)); AlienManager.registerAlien(ailoid); player.setLocation(new Location(400, 400)); } // Paint graphics public void paint(Graphics g) { super.paint(g); } // Thread start @Override public void start() { Thread thread = new Thread(this); thread.start(); } // Thread stop @Override public void destroy() { } // Thread run @Override public void run() { Thread thread = new Thread(this); while (thread != null) { Updater.run(); canvas.repaint(); try { // 1000 divided by fps to get frames per second Thread.sleep(1000 / fps); } catch (InterruptedException e) { e.printStackTrace(); } } } @Override public void keyPressed(KeyEvent evt) { KeyPress.run(evt); System.out.println("DEBUG"); } @Override public void keyReleased(KeyEvent evt) { } @Override public void keyTyped(KeyEvent evt) { } } What happens is that it only starts saying "debug" after I press tab. How would I make it work even if the player doesn't press tab before? What is KeyPress.run(evt);? Draw in the paintComponent(Graphics g) method of a JPanel that the applet displays, This will give you double buffering and reduce flicker. 2) Don't use KeyListeners but rather use Key Bindings since this is a Swing application, and since Key Bindings are more flexible when it comes to focus. Your Applet most likely does not have the input focus.Try adding this.requestFocus () to your init method. Also note that a JApplet is a part of the Swing framework and thus not threadsafe as mentioned in the documentation public static void main(String[] args) { JFrame frame = new JFrame(GAME_TITLE); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); sGame = new Game(GAME_WIDTH, GAME_HEIGHT); frame.add(sGame); frame.pack(); frame.setVisible(true); frame.setIconImage(Resources.iconimage); } I had the same problem, it was caused in main by not calling everything in the correct order. Originally I had setVisible(true) before I had passed sGame to .add and called frame.pack(). This code is what worked for me.
common-pile/stackexchange_filtered
Extension of unitary operator in subsystem to complete system I have a question on an exercise 2.67 in Nielson and Chuang. This is the exercise: Exercise 2.67 Suppose $\:V\:$ is a Hilbert space with a subspace $\:W$. Suppose $\: U : W \rightarrow V\:$ is a linear operation which preserves inner products, that is, for any $\:|w_{1}\rangle\:$ and $\:|w_{2}\rangle\:$ in $\:W$, $$ \langle w_{1} |U^{\dagger}U|w_{2}\rangle= \langle w_{1} |w_{2}\rangle. $$ Prove that there exists a unitary operator $ U' : V \rightarrow V$ which extends $\:U$. That is, $\:U'|w\rangle=U|w\rangle\:$ for all $\:|w\rangle\:$ in $\:W\:$, but $\:U'\:$ is defined on the entire space $\:V$. Usually we omit the prime symbol $\:'$ and just write $\:U\:$ to denote the extension. I'm not being able to figure out how to a) prove it b) construct the extension U' for a given U in a specific problem. Everywhere I search people just refer to the problem or say it's trivial, without giving any direction. $U|w_{1,2}\rangle=|v_{1,2}\rangle$ so $\langle v_2|v_1\rangle=\langle w_2|U^{\dagger}U|w_1\rangle=\langle w_2|w_1\rangle$. And so the unitary operator U' that preserves the inner product for the v's ( $\langle w_2|U^{'\dagger}U'|w_1\rangle=\langle w_2|w_1\rangle$) should be related to U. But what this relationship is eludes me. Or how to find a U' given a U in a subsystem (ie. what $\sigma_x\otimes\sigma_x$ for $2\times 2$ subsystem might translate to as a U' in an $N\times N$ system). The statement is true ONLY if W is finite dimensional. @ValterMoretti Can't we use Hahn-Banach to make the extension even in infinite dimensional spaces? (of course it will not be unique). Consider a separable Hilbert space and take a Hilbert basis $e_1, e_2, \ldots$. Define $W$ as the closed span of $e_2, e_4, e_6,\ldots$ and define $U$ such that $U (e_{2k})= e_k$. How can you extend $U$ as prescribed in the statement? @ValterMoretti Ah ok I see, injectivity problems ;-) Yes, because it is required that the extension is isometric too, so it must be injective and this is not possible. Makes sense that it has to be finite dimensional. But how do we prove it and extend it? Take an orthonormal basis in $W$ consider the image in $V$, complete both bases and extend $U$ in the simplest way... Perhaps rephrasing it makes it easier? A unitary operator $O\colon V\to V$ which preserves the inner product on the restriction $O\restriction W\times V$ ? Oh right, it had the "equal to U on the restriction" constraint as well. We already settled in comments, that this is only true for finite dimensions. Now people say it's trivial, which either means they actually don't know how to do, or it's not very hard but quite technical to write down exaclty and people are lazy, or it is really simple and you should see why. Here, it's a combination of the second and the third. The idea is the following: The condition on $U$ ensures that it sends an orthonormal basis of $W$ to an orthonormal basis of $V$. Hence we can extend it to a unitary map by mapping an orthonormal basis of the complement of $W$ in V, $W^{\perp}$ to an orthonormal complement of the image of $U$, i.e. $\operatorname{im}(U)^{\perp}$. Then the extended $U$ sends an orthonormal basis to an orthonormal basis, which means that it's a unitary. To make this more precise, we know that $W$ is some $m$-dimensional subspace of the $n$-dim. space $V$, hence $W$ too has an orthonormal basis. Let's call this $\{w_1,\ldots,w_m\}$ and remember that it can be extended to an orthonormal basis of $V$ by adding some vectors $w^{\prime}_{m+1},\ldots, w^{\prime}_n$. Now what you need to see is that $U$ maps the orthonormal basis of $W$ to an orthonormal set in $V$. In other words: If $Uw_i=v_i$, then we have $$ \langle v_i|v_j\rangle = \langle Uw_i |Uw_j\rangle = \langle w_i|w_j \rangle =\delta_{ij} $$ In the first step, we used the definition of $v_i$, in the second step we used that $U$ keeps inner products the same and in the third step, we used that the $w_i$ are orthonormal ($\delta_{ij}$ is the Kronecker delta). So $\{v_1,\ldots,v_m\}$ are an orthonormal set, hence it too can be extended to an orthonormal basis of $V$ by adding some orthonormal vectors $\{v^{\prime}_{m+1},\ldots,v^{\prime}_n\}$. But then you can just write down the unitary extension $U^{\prime}$ by setting $U^{\prime}|w^{\prime}_j\rangle=|v^{\prime}_j\rangle$ for $j=m+1,\ldots,n$.
common-pile/stackexchange_filtered
Can't get python server data from android client I want to write a simple android app that sends text to python server and then puts its answer (in our case: how many vowels in the data) and use Logcat to see it really got the data. Everything works just fine excepts for the part where the clients waits for the server response. It just getting stuck there even though the server says it sent the data back to the client. Does anyone have an idea what might have caused this problem? UPDATE: After sniffing with Wireshark I saw that the data the client and server sends to each other is "Malformed packet". Anyone knows why? my client code: public class MainActivity extends Activity { private Socket socket; private static final int SERVERPORT = 5000; private static final String SERVER_IP = "<IP_ADDRESS>"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new Thread(new ClientThread()).start(); } public void onClick(View view) { try { EditText et = (EditText) findViewById(R.id.EditText01); String str = et.getText().toString(); PrintWriter out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())), true); out.println(str); Log.i("Tag","sent " + str); BufferedReader input = new BufferedReader(new InputStreamReader(this.socket.getInputStream())); try { String read = input.readLine(); Log.i("Tag","got " + read); } catch (IOException e) { e.printStackTrace(); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } class ClientThread implements Runnable { @Override public void run() { try { InetAddress serverAddr = InetAddress.getByName(SERVER_IP); socket = new Socket(serverAddr, SERVERPORT); } catch (UnknownHostException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } } } my server code: import socket srv_sock = socket.socket() ip = "<IP_ADDRESS>" # means local port = 3001 # 0 means get random free port srv_sock.bind((ip, port)) srv_sock.listen(5) while True: (new_sock, address) = srv_sock.accept() print "Hello! this is a vowels server! You need to send a word or a sentence and I'll give you the number of vowels in it!" while True: data = new_sock.recv(1024) if data == "" : print "Client Disconnected" break print "Received<<< " + data data = data.upper() to_send = "Num of vowels is " cnt=0 if data.isdigit(): to_send = "ERROR:Number doesn't have any vowels!" else: for letter in data: if (letter == 'A' or letter == 'E' or letter == 'O' or letter == 'U' or letter == 'I'): cnt += 1 to_send += str(cnt) new_sock.send(unicode(to_send + "\n")) print "Sent >>>" + to_send new_sock.close() srv_sock.close() If it's pretty clear, then enlighten me... If you want something in return except for thanks, then I don't need your help... ah lol... it is just a figure of speech. So can you help me? txt.setText(data);. Your app should crash on that statement. And in the logcat you should find the stacktrace and exceptions. You cannot do that gui action in the run() of a runnable. Take it out or use runOnUiThread(). thanks but that's not my problem. the problem is the app doesn't even enter the while part, that means it doesn't get answer from the server No. That probably means that there is no connection to begin with. Do you see this log statement? Log.i(Tag,"connected");. Yes. I get all the logs except for this one 'Log.i(Tag, "got data: " + data);'. Also I see in the server side that it got what the client sent him and it sends a response Please tell exactly what the server sends as response. That code is much to cryptic. You use writeUTF() and readUTF() in your client. Where in your python code can we see that python expects such utf strings and also sends them? I hope you realize that such utf strings are different from normal strings. The server sends the sentence: "Num of vowels is" + num of vowels in the data new_sock.send(to_send.encode("UTF-8")) makes the data unicode which method should I use to get string data as ascii not unicode? writeUTF() first sends some bytes indicating the length of the following string. readUTF() first reads some bytes so it knows the length of following string. I was not talking about unicode or ascii. I didn't know it... Doesn't UTF means unicode? Is there any other way to send and recieve strings? Yes there is. But what i do not understand is that if i tell you that the client sends some size indicating bytes for every string the receiver should receive them first too. Now did you see them at server side? You can just use out.write(). After a long time, I decided to start all over again. I updated the client code. The server gets the data and sends back a response which I cannot get. It stucks on the input.readline(). In wireshark it says "Malformed packet". Any idea why it happens and how to fix it? If a client tries to read a line then the server should have send one. Now did the server? Yes, the server sent a response (it prints te sent data as an evidence), but again in Wireshark it says the packet is 'malformed packet'. The server should send a line as response. Now does the server send a line? I think so. It prints the line after it sends it It looks as if you do not understand what i mean by sending a line. A line is not just some characters. And the receiving side is trying to read a line. Not just some characters. Again: if the server does nkt send a line then the clientcannot read a line. Please explain what a line is. You are right - I thought a line is just a string. Can you please explain what it really is? A line is a string that ends with a new line character. Like in a text editer. If you press the enter key you start on a new line. String "this is a line\n"; So if the receiving side is trying to read a line with readLine() then it waits until the new line character \n is found. Which you did not sent until now. changed it to send unicode(to_send +"\n") but it still doesn't work. also tried to send ascii Your code can never work. The server will receive nothing from your client. And your client will crash with a NetworkOnMainThreadException. Can you please explain me why it receives nothing and how to solve it? The server will receive nothing from your client. You did not confirm or deny that. And your client will crash with a NetworkOnMainThreadException. You did not confirm or deny that. You did not even comment. Difficult helping in this way. Already told you that the server gets the data from the client and even sends it back. About the exception, it doesn't crash. What do you think is the problem with my code? The network code in onClick() should give a NetworkOnMainThreadException which would let your app crash. Please explain why you would not get one. Are there things you did not tell us but should? Wow, I forgot to check if I get an exception,now I do all the communication part in the ClientThread runnable and it finally worked. Thank you for your help!
common-pile/stackexchange_filtered
Regular expression is too large I'm having issue with this function, function _where($arg, $separator = ' '){ if ($arg['where']){ $operators = '( |=|!=|<>|<|<=|>|>=|=~|!~|\?|\?!)'; foreach ($arg['where'] as $k => $v){ if (preg_match('/\[(.*)\]/i', $v, $match)){ foreach (explode('|', $match[1]) as $or){ $where[] = preg_replace('/(.*)'.$operators.'(.*)/i', '\\1\\2\'\\3\'', preg_replace('/\['.str_replace('|', '\|', $match[1]).'\]/i', $or, $v)); } $result[] = '('.join(' or ', $where).')'."\r\n"; } elseif ($v != 'and' and $v != 'or' and $v != 'xor'){ $result[] = preg_replace('/(.*)'.$operators.'(.*)/i', '\\1\\2\'\\3\'', $v)."\r\n"; } else { $result[] = $v."\r\n"; } } return 'where '.str_replace(array('!~', '=~'), array('not like', 'like'), join($separator, $result)); } } And is resulting in, PHP Warning: preg_replace() [<a href='function.preg-replace'>function.preg-replace</a>]: Compilation failed: regular expression is too large at offset 63088 I am running another site with same code, and issue doesn't exist there, is this issue related to the number of row in db? No, the issue is because of PHP version. You're probably running older PHP version, when you get that error. Bottom line: You're implementing your query builder in wrong way. Look at Zend Framework 2/Db how they implement where() clause If it was a DB issue, then you'd get a DB error, not a PHP error. PHP couldn't care less what the DB's capable of. It just sends the query and sees what happens. If the query fails, PHP doesn't care. /\[(.*)\]/i should most probably be written as /\[(.*?)\]/i. As it's written now, it consumes all the text between the first bracket and the very last one, hence an error. And instead of str_replace to escape | you should use preg_quote. Can you give the original string and the expected result for this function. Thank you all, The issue was with how PHP queried MySQL, I had to re-write some SQL queries and issue has been resolved now. The issue was with how PHP queried MySQL, I had to re-write some SQL queries and issue has been resolved now. by the OP D_Guy13 in this comment
common-pile/stackexchange_filtered
Bit manipulation to determine if all "movement" of set bits was to the left When a binary integer's value changes, we can describe that change as "only left movement" if the new value can be formed using only these two operations: Clear a set bit Clear a set bit, and then set any unset bit to the left of the bit that was cleared Some examples: 10101010 -> 10101100 # valid 10011000 -> 10010000 # valid 11111111 -> 00000001 # valid 00000000 -> 00010000 # invalid 10000011 -> 01110000 # invalid 10001010 -> 10101100 # invalid I have this function that works fine (for non-negative 32-bit integers): def only_left(a, b): a, b = bin(a)[2:][::-1].zfill(32), bin(b)[2:][::-1].zfill(32) ac = bc = 0 for i, j in zip(a, b): ac += int(i == '1') bc += int(j == '1') if bc > ac: return False return True My question is, can this be done without any type conversion or loops, using only bitwise and arithmetic operators (& | ^ ~ + - * / %)? I know the function above can be written using >> and & in a loop, but I'm wondering if it's possible to do this in one step (no loops). I am not sure that i understand the examples. Can you explain some more as to which bits are set and which are cleared and why it is valid or invalid. Also, if you have this algorithm in a loop, Why do you need it without a loop. And why is there a restriction on using only arithmetic operators? Doesn't this come to case where the bit strings on the left should always be greater than the ones in right? invalid if they are not? Your code return True for 00000000 -> 00010000 Can you clarify the wording of your rules? What do you mean by "Clear an unset bit"? The gist seems to be that the only way to have 0->1 is as part of 01 -> 10. Is that correct? Original wording was “clear a set bit.” I updated the question with a corrected function that should handle the case ikegami mentioned, and reverted the wording. Can you explain how 11111111 -> 00000001 # valid is valid? From your question I thought only one bit could be reset. @J...S The two operations described can be executed zero or more times.
common-pile/stackexchange_filtered
C# wpf mvvm programmatically change border color programmatically I'm a beginner - I have a Border with an image inside, there could ultimately be many of these border/photos in xaml code. The border(s) have an attribute Name="Border_N" (N = a unique border id value) I'd like to click on this photo which is a button and have the border change colour. I want to be able do this programmatically but, I'm really not sure how best to go about this. I'm sure this can't be difficult, but I'm really not sure where to start. Anyone know? First of all, you should clarify your requirements. What happens on the second click? Does the color change back to the value it had before the first click? Then consider using a ToggleButton. If it is a ToggleButton, bind the Border's BorderBrush to the IsChecked property of the ToggleButton with an appropriate Binding Converter. This is a fair point. So far I have been able to display an ObservableCollection of names from MySQL to my MainWindow. Each name has an Id. When I click on it, I want to send this names Id back to MySQL and change the Border color. "What happens on the second click?" ...to be continue. If you are a beginner, learn MVVM. As the meme says, first you have to learn the rules, so that then you can break them like a pro. If you try to start by breaking the rules you are in for big disappointment and great pain. And chances are, that once you have learned the rules, you will not even have the desire to break them, because you will see that MVVM does in fact make GUI development so much easier. You do not want to change your border color programmatically. You do not even want to change your border color when something is clicked. What you want to do instead is to introduce some state in your viewmodel, which represents the fact that "this photo" is clicked, (say, bool ThisPhotoIsClicked { get; set; }, hopefully you will find a more meaningful name,) and then you want to make your border select its color based on that state. For this, you have a couple of options: You can bind the color of the border to the state using a binding with a boolean-to-color converter (see https://stackoverflow.com/a/32526689/773113) You can assign a style to your border which incorporates triggers to realize different colors based on different states (see https://stackoverflow.com/a/8534694/773113) If he just wants to highlight every clicked photo and never wants to go back, introducing MVVM is an overkill IMO. Handling Visuals in code behind is perfectly fine. Sure he should consider using MVVM if it is appropriate but how do you know? I'm trying to learn the mechanisms, so to speak. I've used MySQL, added images to buttons etc. If I can work out how to effect a xaml border or label or anyting else programmatically I'll be very happy. @lorenzalbert I begin with the axiom that WPF cannot legitimately be used without MVVM, and more broadly, that GUI development is only worth doing using MVVM. In the past I have used C++/Win32 GDI, C++/MFC, C#/WinForms, Java/Swing, and Java/SWT, so trust me when I say, that's the way to go. @user1192941 yes, and precisely because you are trying to learn the mechanisms I am pointing you to The Mechanisms. If it was obvious from your question that you were already quite familiar with The Mechanisms and you are now just looking for some hacky workaround to bypass The Mechanisms and haphazardly accomplish something in a quick and dirty way, then maybe my answer would have been different. "quick and dirty" is not my way. I am trying to learn MVVM as mentioned. Changing visuals from within the codebehind is not quick and dirty. This also follows the MVVM principle. What you need depends on your use case. As a beginner I'd tell you: "Discover the different functionalities like ClickEvents, how to change visuals from the code behind. Then go on to MVVM and learn how to use Bindings and when to use Commands". Same goes for TDD, IOC and so on. Noone starts learning how to code by jumping into these topics.
common-pile/stackexchange_filtered
What this string means? ua:fa95ebdb-6da9-498c-aabb-77c7baaa28d3 When I woke up this morning, this "code" was the last text copied to my phone (Samsung, Android version 12), of course it was not me who copied this string, and I spent the night alone. I saw this when opening the GBoard keyboard, which offered to paste it. I didn't enable clipboard with this keyboard, so it was less than an hour before I woke up. At first I thought it was me accidentally writing this text while sleeping (my phone is next to me all night, not turned off). But looking closer, I saw that it is a hex code. While searching on the net, I saw that ua can mean "user agent" but impossible to find what this hexadecimal string means... Does anyone know this kind of string? Or would have any idea what could have happened to cause this to end up being copied to my phone? I admit it scares me... The format of this string is called "UUID" (universally unique identifier), or "GUID" (globally ...) in some places. It represents a series of 128 bits which are usually chosen at random when a unique ID for anything is needed. The collision probability on 128 random bits is so low that they are considered unique (or more precisely: unique enough) even without a central coordinating instance that guarantees global uniqueness. That being said - if "ua:" stands for "user agent" in this case, then it seems to be a string identifying your browser, and it might have gotten into your clipboard from a badly programmed tracking script on some website you visited. Thank you so much for this context and your detailed answer! Exactly what I was searching for This looks like an app's internal ID (GUID) to identify an entity. Within the context of the app in question,n copy and pasting something will result in an entity with that ID being copied. But if you paste it externally to the app, you will see the entity's ID. This is a common technique for app development.
common-pile/stackexchange_filtered
how to create a pop-up that displays a generic information I have a table that contains the fields below and I created a model using EF: Event Details EventMngID Event_name Event_location Event_Date EM_opt1Question1 EM_opt1Answer1 EM_opt1Question2 EM_opt1Answer2 EM_opt1Question3 EM_opt1Answer3 EM_opt1Question4 EM_opt1Answer4 I have a page that display the event Information and custom question they are in seperate division. As you can see, the second image has a Edit Choices action link. When I click the edit it will display a pop-up that displays the answers. From the pop-up I can modify the values and save the answer. All changes should reflects in the Answer Field dropdownlist of the Custom Question division. My problem here is, what is the mechanism to use, since the table contains 4 answer field if will I going to do like this in the pop-up (below code) then what about the Answer2 ..4? And I am sure it will raised an error. Any help please on how to solved this problem or if there is a link that is related to my problem please send it to me. <div class="editor-field"> <%: Html.TextBoxFor(model => model.Answer1) %> <%: Html.ValidationMessageFor(model => model.Answer1) %> </div> Why not use Jquery UI and more specifically, the Dialog? http://jqueryui.com/demos/dialog/ I am using jquery dialog for the pop-up I'm not sure what you are asking. Are you asking how to store multiple answers per question? Or are you asking about some sort of validation on the answers? Well, I am asking on how to display the answer in the pop-up window. For eg, If my field is opt1Answer1 it will display the opt1Answer1 values, if my field is opt1Answer2 then it will display the opt1Answer2 values and so on The way I see it, you have two options. The first (which I do not think is the best option) is to figure out which question and answer number is being edited and generate your query dynamically. I'm not sure if you are using some ORM like Entity Framework but if you are, you will then need to have some long if/elseif statement like the following: if (editing question 1) return (query to get question and answer 1) else if (editing question 2) return (query to get question and answer 2) On the other hand, if you are just writing the sql queries dynamically and using ADO.NET, you can generate the query text a bit easier. Again, I DO NOT RECOMMEND THIS SOLUTION. The better solution would be to normalize your database and separate the questions and answers into their own table and not lump them into the EventDetails table. You would need to remove each EM_opt1QuestionX and EM_opt1AnswerX columns from the table and create a new table with some structure like the following: QuestionAnswer -------- QuestionAnswerID EventMngID Question Answer Then each question and answer has their own id which allows you to easily target a given record. This also allows you to have as many or as few questions and answers as you need without having to try and guess the maximum number of questions that would be needed. Actually that is also my idea, but the client designed it and they didn't allow to modify the structure of the table
common-pile/stackexchange_filtered
Jquery click event propagation on second click after Ajax Hi i always use this example code to make a div work as link. <div onclick="location.href='http://www.example.com';" style="cursor:pointer;"></div> The problem is i have inserted an other javascript action inside (this action need to stay on the current page) the problem is Not the first click but the second.. This javascript actions its an ajax function that "change" that html.. in the fiddle where i have no ajax, its working great, on first, second, third, any clic.. Here is the code http://jsfiddle.net/HzsH9/4/ Im using.. Jquery, also this is the anti propagate code im using $("a").bind("click", function(e){ alert("clicked!"); e.stopPropagation() }); The outer div class is class="listingsRow" and the inside javascript goes here <a id="btn_remove_114" name="btn_remove_114" onclick="ajaxFavouratesRemove(1,114,375);"> <div class="fav"></div></a> After ajax success, its changed for this <span id="spadd114"><a id="btn_add_114" name="btn_add_114" onclick="ajaxFavouratesAdd(114);"><div class="nofav"></div></a></span> Also i just found this, but i cant manage to do the same how to stop event propagation with slide toggle-modified with the updated code. click events propagate down the DOM, so it's not surprising it reaches the div element before the a element. what? no. events propagate up. and eventually reaches window. I'm sorry, but I don't understand the question. could you try to be a bit more clear as to what you want? In your fiddle, it seems to be acting in the way you want it to. The click event on the yellow box doesn't propagate beyond the <a/> tag. Classic case of event delegation $(".listingsRow").on('click','a',function(e){ alert('clicked'); e.stopPropagation(); }) Thanks but is not working.. after the alert im redirected to the URL , im not avoiding redirection $('#singles_114').click(function(e){ e.stopPropagation() }); Thanks but for each item i need a different id than 114? is there a way to set for "anynumber" declare all items with different ids like 114,115..etc, and on the click call the same function, next inside that function using jquery attr() get the id and use it like based on your requirement. Sorry if my english is bad.
common-pile/stackexchange_filtered
Zend_Db_Select EXISTS One part of my query is EXISTS condition: $select->where( 'EXISTS(' . 'SELECT `price_property_id` FROM `property_price` ' . 'WHERE `price_property_id` = `pu_property_id`' . ' AND `price_value` >= ' . $params['price_min'] . ' AND `price_value` <= ' . $params['price_max'] . ')' ); How it writes in right way in Zend Framework? As far as I know, Zend_Db_Select doesn't have specific methods to include subqueries in the where clause. I think you cannot improve it any further, the way it's written. You might rewrite the subquery as an OUTER JOIN, and you'd be able to leverage some more Zend_Db_Select methods, but I'm not sure about the advantages of doing it, as far as your code is working and clear to read. Hope that helps, I create my sub queries and sub selects as new Zend_Db_Select objects. This make the code slightly cleaner as I can potentially reuse that query elsewhere, it also helps with debugging as I can echo (string)$subQuery to review just that part of the SQL. $subQuery = new Zend_Db_Select(); $subQuery->from(array('price' => 'property_price')) ->where('price_property_id = pu_property_id') ->where('price_value >= ?', $params['price_min']) ->where('price_value <= ?', $params['price_max']); $select->where('EXISTS('.$subQuery.')'); $select->where('EXISTS('.$subQuery.')'); is failing because $subQuery is not a string (in ZF2 at least) I believe this is what you're looking for!: <?php // $select is instance of Zend_Db_Select // $db is instance of Zend_Db_Adapter $select->where('exists (?)', new Zend_Db_Expr( $db->quoteInto('select * from your_table where id = ?', $id, Zend_Db::PARAM_INT) )); ?>
common-pile/stackexchange_filtered
Difficulty displaying an Input with Icon using Lightning Design System I'm working on creating a Visualforce page that uses the Lightning Design System. As part of the VF page I'm trying to include an text input field which the user will use to input search terms. I would like to use the Input with icon to the right displaying a magnifying glass icon per the standard SLDS markup. <div class="slds-form-element"> <label class="slds-form-element__label" for="text-input-01">Input Label</label> <div class="slds-form-element__control slds-input-has-icon slds-input-has-icon--right"> <svg aria-hidden="true" class="slds-input__icon slds-icon-text-default"> <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/assets/icons/utility-sprite/svg/symbols.svg#search"></use> </svg> <input id="text-input-01" class="slds-input" type="text" placeholder="Placeholder Text"> </div> </div> My problem is that the input field does not display at all. When I inspect the element I find that the input field is being placed inside the svg tag. I have found that if I put a span or div tag around the input tag then the input tag will be outside of the svg tag like it is supposed to be and it will display the input box but the magnifying glass icon does not display. I have the most recent version of SLDS and the markup is directly copied from the Lightning Design System website. What is going wrong and how can I get the magnifying glass to display properly? In this line of code, this path should refer to your SLDS library which you uploaded in Static resources. <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/assets/icons/utility-sprite/svg/symbols.svg#search"></use> For example: <use xlink:href="{!URLFOR($Resource.SLDS100, '/assets/icons/custom-sprite/svg/symbols.svg#custom3')}" /> ,< Why is it always the stupidest things. argghh. So that gets me the magnifying icon when my input is surrounded by span tags. Any idea why when I remove the span tags the input tag gets shoved inside the svg tag? hmm. not sure about that @SFNinja now that SLDS is baked into Lighting Experience, how would we go about this sort of thing now?
common-pile/stackexchange_filtered
three.js shadowCascade usage I'm trying to use shadowCascade for directional lights. Using any code of the examples mentioned in https://github.com/mrdoob/three.js/issues/1888 results in a shader error + a periodical error Object [object Object] has no method 'decompose'. Since it's a seldomly used and undocumented feature I have no clue where to even begin with debugging. Even leaving all the code out and enabling shadowCascade in the console for the light while the scene is running results in the periodical error from above showing up. Any help would be greatly appreciated! Kind regards, Doidel PS: People always want to see some code. So here's some code. var sunlight = new THREE.DirectionalLight(); sunlight.intensity = 0.5; sunlight.position.set(100, 300, 100); sunlight.castShadow = true; sunlight.shadowBias = -0.0001; sunlight.shadowMapWidth = sunlight.shadowMapHeight = 2048; sunlight.shadowDarkness = 0.7; var d = 250; sunlight.shadowCameraLeft = -d; sunlight.shadowCameraRight = d; sunlight.shadowCameraTop = d; sunlight.shadowCameraBottom = -d; sunlight.shadowCameraNear = 200; sunlight.shadowCameraFar = 800; sunlight.shadowDarkness = 0.6; sunlight.shadowBias = 0.000065; sunlight.shadowCascade = true; sunlight.shadowCascadeCount = 3; sunlight.shadowCascadeNearZ = [ -1.000, 0.9, 0.975 ]; sunlight.shadowCascadeFarZ = [ 0.9, 0.975, 1.000 ]; sunlight.shadowCascadeWidth = [ 2048, 2048, 2048 ]; sunlight.shadowCascadeHeight = [ 2048, 2048, 2048 ]; sunlight.shadowCascadeBias = [ 0.00005, 0.000065, 0.000065 ]; sunlight.shadowCascadeOffset.set( 0, 0, -10 ); scene.add( sunlight ); sunlight.lookAt(new THREE.Vector3(0,0,0)); Does this work: http://threejs.org/examples/webgl_morphtargets_md2_control.html ? Uhm that's one of the two examples mentioned in the thread I linked. But yeah, that one doesn't work too if I copy it 1:1. You don't have these errors? Does the light work for you? I linked to a three.js example that works with the current version r.58. You linked to to a different site, using a three.js version that is a year old. You are most likely linking to an old version of the three.js library. Use r.58. Hmm I happened to have r58 already. And now I took the code from that demo 1:1 and I still get the same issues.. I'll search on, maybe I find something. Or I'll post some progress if I don't find anything... Ok here's my console output: http://pastebin.com/ywv6XbmE Yes, the three.js r.58 demo works for me, excpet for a visual bug using Chrome 27. Look at line 307 then 313-317 of my pastebin. Does that make any sense to you..? But strangely nowhere in the code "max shadows" is set, in the example! Lines 313-317 are mostly blank. Can you provide a live link to your example? There was another discussion about the usage of shadowCascade with the conclusion to currently not use shadowCascade, due to not being maintained.
common-pile/stackexchange_filtered
Git - fatal: Unable to create '/path/my_project/.git/index.lock': No such file or directory read tree xxxx command returned error: 128 I'm converting my SVN repo into git (bitbucket) following this tutorial: https://www.atlassian.com/git/tutorials/migrating-convert/ But I keep getting this message when runing the command : git svn clone --stdlayout --authors-file=authors.txt --prefix=origin/ I'm having the same problem. Did you ever find a solution? Does this solution help? http://stackoverflow.com/questions/13457910/git-svn-importing-a-branch-with-a-trailing-space Yes, thanks. I found that later that day and solved the problem. Wish I could cancel my bounty. :) Thank you for the bounty..:-) The answer is somewhat explained in the comment. Similar issues are experienced on Windows system due to its limitations like: Some of the Windows APIs are limited to 260 symbols for file path name. So git can't create files with names longer than 260 symbols. NTFS file system actually supports longer names (32k). Windows directory allows Space in between like my folder. Windows file and folder names that begin or end with the ASCII Space (0x20) are saved without these characters. Some of the Workarounds are: Move the git directory closer to the drive, in order to keep the file name within 260 symbols. Creating the whitespace directory manually using tools like FAR, GnuWinwhich can make a directory Reference: Support for Whitespace characters in File and Folder git svn importing a branch with a trailing space git checkout error: unable to create file
common-pile/stackexchange_filtered
Given two metric, $d_1$ dominates $d_2$ and $X$ is complete w.r.t. $d_1$, then $(X, d_1)$ is complete, then $(X, d_2)$ is complete? Given a space $X$ and metric $d_1, d_2$, suppose $d_1 \leq d_2$. Also suppose $(X, d_1)$ is complete. Then, is it true that $(X, d_2)$ is complete? Attempt: Take Cauchy sequence $\{x_n\}$ in $(X, d_2)$. Then, the sequence is Cauchy in $(X, d_1)$. Hence, $x_n \rightarrow x_0$ in $(X, d_1)$. I am stuck here since I cannot conclude $x_n \rightarrow x_0$ w.r.t. $d_2$. I suspect that an extra condition is needed. Maybe this can help. Let $X=\{2^{-n}:n\in\Bbb N\}$, and let $d_2$ be the usual Euclidean metric on $X$. (Note that $0\in\Bbb N$.) Define a metric $d_1$ on $X$ as follows: $$d_1(2^{-m},2^{-n})=\begin{cases} |2^{-m}-2^{-n}|,&\text{if }m=n\text{ or }m\ne 0\ne n\\ 2^{-m},&\text{if }n=0\\ 2^{-n},&\text{if }m=0\,. \end{cases}$$ It’s easy to check that $d_1$ is a metric: either directly or by observing that it is simply the Euclidean metric on $\{0\}\cup\{2^{-n}:n\in\Bbb Z^+\}$ transferred to $X$ by the bijection $h$ defined by setting $$h(y)=\begin{cases} y,&\text{if }y\ne 0\\ 1,&\text{if }y=0\,. \end{cases}$$ Clearly $d_1(2^{-m},2^{-n})\le d_2(2^{-m},2^{-n})$ for all $m,n\in\Bbb N$, and $\langle X,d_1\rangle$ is compact, so it is complete, but $\langle 2^{-n}:n\in\Bbb N\rangle$ is a Cauchy sequence in $\langle X,d_2\rangle$ that does not converge in $\langle X,d_2\rangle$. As drhab suggested in the comments, you need an extra hypothesis in order to be able to conclude that $\langle X,d_2\rangle$ is complete, and one that works is the hypothesis that for each $x\in X$ and $r>0$, the closed $d_2$-ball $\{y\in X:d_2(x,y)\le r\}$ is also closed in the metric $d_1$; see the answer to this question.
common-pile/stackexchange_filtered
Can I get NL Student visa after UK visa refusal? After trying and being refused twice for tier 4 visa in the UK, both on finance reasons, my plight can be read about here (UK student visa refusal) I'm looking at applying to university else where in Europe, and the Netherlands have a couple universities that I like. Will it be a problem for me if I declare everything and is truthful on my application form? The UK refusals should not be a problem of themselves. The most likely possibility is that the circumstances you showed to the UK, which were inadequate and resulted in a refusal, will also be inadequate for the requirements of the Netherlands, and will therefore result in a refusal there as well. On the other hand, it's possible that the Netherlands evaluates such circumstances differently, and might therefore accept your application. Above all, you should not try to hide your history with the UK. You will very likely be found out, and a visa refusal for deception will make it difficult for you to get a visa anywhere for a very long time, perhaps for the rest of your life. Your experience with the UK shows that your financial situation is complicated, and that your applications were not always optimally prepared (in particular, you didn't always have a full understanding of the rules governing your application). You are likely to have a better shot at approval if you hire a reputable professional to prepare the application. You should most likely look for an immigration lawyer in the Netherlands rather than an agent in your home country, since we have heard many stories of such agents being unscrupulous, or at least insufficiently familiar with the rules of the foreign country with which the visa application is being filed. For a local lawyer, the country isn't foreign, and the lawyer is a specialist in the law of that country. By the time of application of Netherlands visa I will 18 and be able to have my parents transfer the money into a bank account in my name. Will that help the situation? as I no longer need to prove the association or anything like that. The money was always there and ready to use, the only problem we seemed to have was showing that I had access to it. @phoog @A.Ren I think you have misinterpreted your refusal notices. All the more reason to get professional assistance.
common-pile/stackexchange_filtered
Can't set SelectedValue in combobox using objects I have the following code : public partial class ModificarAlimento : Form { private Alimento alim; private Dictionary<string, Nutriente> nutrientes; public ModificarAlimento(Alimento a, Dictionary<string, Nutriente> nut) { InitializeComponent(); this.nutrientes = nut; alim = a; int i = 0; foreach (KeyValuePair<string, CantidadNutrientes> x in alim.Nutrientes) { ComboBox n = new ComboBox(); n.DropDownStyle = ComboBoxStyle.DropDownList; n.Location = new Point(12, 25 * (i + 1) + 80); n.DataSource = new BindingSource(nutrientes, null); n.DisplayMember = "Key"; n.ValueMember = "Value"; TextBox cNuts = new TextBox(); cNuts.Location = new Point(150, 25 * (i + 1) + 80); cNuts.Size = new Size(50, cNuts.Size.Height); cNuts.Text = x.Value.Cantidad.ToString(); this.Controls.Add(n); this.Controls.Add(cNuts); i++; n.SelectedValue = x.Value.Nutriente; } } private void ModificarAlimento_Load(object sender, EventArgs e) { } } Now. The problem is here: n.SelectedValue = x.Value.Nutriente; Each Alimento (Food) has a dictionary set of CantidadNutrientes, which stores a double value and a Nutriente (Nutrient), which in turn stores a name. So, calling x.Value.Nutriente will retrieve the Nutriente in the CantidadNutrientes stored in x. Why isn't this working? Any help is appreciated. EDIT: I'm also trying this n.SelectedIndex = n.FindStringExact(x.Key); //and n.SelectedValue = n.FindStringExact(x.Value.Nutriente.Nombre); However for some weird reason it works while I debug, but if I don't go through line for line it doesn't work at all. Try putting n.CreateControl(); before this.Controls.Add(), and put n.SelectedItem = n.Items .Cast<KeyValuePair<string, Nutriente>>() .SingleOrDefault(o => o.Key == x.Key); after call to this.Controls.Add() You're welcome, I edited it not to use Items.IndexOf because it's simpler this way. You must use ComboBox.Text or ComboBox.SelectedIndex: combox.SelectedIndex = combox.FindStringExact("yourItem"); or combox.Text = "yourIetmText"; note that: ComboBox.FindStringExact Method can help you to finds the item index that exactly matches the specified string. I believe you meant ComboBox.SelectedIndex Either way doesn't work. I can't set the text (it's a DropDownList) and I can't select the index (I'm working with a dictionary so I have no information on "which number" is each entry). When I go through line by line while debugging it, this works, but if I execute it without debugging it just doesn't work... Please use comboBox1.SelectedText instead this set the item and plus show as edited text in the combo n.DropDownStyle = ComboBoxStyle.DropDownList; Hence I cant.
common-pile/stackexchange_filtered
Cannot create Bitbucket repository in team as developer using API I have a Bitbucket account named myaccount. I am a developer of a team named ateam which does not belong to me. I am not an admin of this team. Developers have their permissions set to create repositories in ateam. I am able to manually create a repository in ateam through bitbucket website's UI. However I am unable to do so using bitbucket's API: $ curl -X POST -v -u myaccount:mypasswd https://api.bitbucket.org/2.0/repositories/ateam/rep1 -H "Content-Type: application/json" -d '{"is_private": true}' Enter host password for user 'myaccount': * Trying <IP_ADDRESS>... * Connected to api.bitbucket.org (<IP_ADDRESS>) port 443 (#0) * TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 * Server certificate: *.bitbucket.org * Server certificate: DigiCert SHA2 High Assurance Server CA * Server certificate: DigiCert High Assurance EV Root CA * Server auth using Basic with user 'myaccount' > POST /2.0/repositories/histeam/rep2 HTTP/1.1 > Host: api.bitbucket.org > Authorization: Basic YWxleGFuZHJlLW5hZGluOmJpdGJ1Y2tldDEy > User-Agent: curl/7.43.0 > Accept: */* > Content-Type: application/json > Content-Length: 20 > * upload completely sent off: 20 out of 20 bytes < HTTP/1.1 403 FORBIDDEN < Server: nginx/1.6.2 < Vary: Authorization, Cookie < Content-Type: application/json; charset=utf-8 < Strict-Transport-Security: max-age=31536000 < Date: Thu, 14 Jul 2016 09:59:27 GMT < X-Served-By: app-111 < X-Static-Version: 53f44cd8792e < ETag: "2517d8a35dee8cb8cd9e5f0c889915ba" < X-Render-Time: 0.0265378952026 < X-Accepted-OAuth-Scopes: repository:admin < Connection: keep-alive < X-Version: 53f44cd8792e < X-Request-Count: 317 < X-Frame-Options: SAMEORIGIN < Content-Length: 35 < * Connection #0 to host api.bitbucket.org left intact {"error": {"message": "Forbidden"}} I have forbidden access. Now the owner of ateam made me the team's administrator. Since then I am able to create a repository in ateam with the very same command as above: $ curl -X POST -v -u myaccount:mypasswd https://api.bitbucket.org/2.0/repositories/ateam/rep1 -H "Content-Type: application/json" -d '{"is_private": true}' The point is I need to create a repository using the API as a developer, not as an admin. It works using the website's GUI but not through the API: Despite having permissions to create repositories, developers are forbidden to do so using the API. So do we have a bug here? If not, am I missing something? EDIT 1 Here is a screenshot of the Developer's permissions on the team. As one can see, they are supposed to be able to create a repository. As far as I know only admins can create repos. That is untrue, I attached an image to show you the devs' permissions on the team. Any dev can create any repository in the team using the web interface. We need to do so with the API, which is forbidden for some reasons. Bitbucket developer here. I agree that that is a bug. And I am actually personally responsible for it :(. So, apologies for that. I have made a fix and it will be deployed in the next deploy (probably this Tuesday). Kind regards. Nice thank's a lot! I'm looking forward for the fix ;)
common-pile/stackexchange_filtered
Check if email is in database in custom express-validator. (node, express, mysql) //Update the user's email endpoint. apiRouter.post('/update-email', [ check('newEmail') .isEmail().withMessage('Please Insert a valid Email') .custom(newEmail=> { db.query(`SELECT user_id FROM users WHERE email = ?`, newEmail,(err, res)=> { if(res.length > 0) throw new Error('Email is already registered.'); }); }) ], (req, res)=> { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(422).json(errors); } else { const newEmail = req.body.newEmail; const id = req.body.id; userCRUDfuncs.updateEmail(id, newEmail, db, (err=> { if(!err) { return res.status(201).send(); } else { return res.status(404).send(); } })); } }) This code returns the following error: "throw err; // Rethrow non-MySQL errors". I have tried using callbacks and Promises but I can never throw the error outside the query function. I could not find a way to signal the outside function to throw the error. I really appreciate your help on this . Thanks in advance. Make your own custom validator and wrap your query inside a promise .custom((value, {req}) => { return new Promise((resolve, reject) => { db.query(`SELECT user_id FROM users WHERE email = ?`, req.body.email,(err,res)=> { if(err) { reject(new Error('Server Error') } if(res.length > 0) { reject(new Error('E-mail already in use')) } resolve(true) }); }); }) Thank you very much Rohit. I had tried async await but was giving me trouble. Mark it as the correct answer if it helped you :) Might help future readers. @EmanuelFaísca
common-pile/stackexchange_filtered
Merge Sort in C compiles, but doesn't sort I made this program to sort an array. It works fine, but it won't sort! Please help me find the error in my logic. Thanks [UPDATE] It was able to work! I just brought down the i, j, and k as suggested below.Also, from i #include <stdio.h> #include <stdlib.h> void mergesort(int[], int, int); void merge(int [], int low, int mid, int hi); //function prototype int main() { int arr[]={1,4,78,92,9}; mergesort(arr,0,5); //after mergesort for(int i=0; i<5; i++) { printf("%d, ", arr[i]); } system("pause"); return 0; } void mergesort(int aptr[], int low, int hi) { int mid =0; int rightmax=0; int leftmax=0; if(low==hi) { return; } mid=(low+hi)/2; mergesort(aptr, low, mid); mergesort(aptr, mid+1, hi); merge(aptr, low, mid, hi); } void merge(int aptr[], int low, int mid, int hi) { int j, i, k; //copy contents of aptr to auxiliary b for(i=low; i<=hi; i++) { bptr[i]=aptr[i]; } // iterate through b as if they were still two arrays, lower and higher //copy smaller elements first i=low; j=mid+1; k=low; while(i<= mid && j<=hi) { if(bptr[i]<=bptr[j])//<--put smaller element first { aptr[k++]=bptr[i++]; } else { aptr[k++]=bptr[j++]; } } // copy back first half just in case while(i<=mid) { aptr[k++]=bptr[i++]; } }//function How can the program work fine if it doesn’t sort? ;-) @Billy: I agree with your brace style. Thanks for the edit. :-) @Cody: Go Allman style! :) Seriously though I won't usually mess with style unless the posted code has a lack of any consistent style. You're very welcome for the edit though. The statement i<= mid && j<=hi is never true when your program executes, hence, the while loop that depends on it is never entered and your code that actually swaps elements is never reached. After the for loop that precedes it, i is equal to hi, which is always greater than mid. I am guessing you mean to reset i to be equal to low before you enter that while loop. Here's a suggestion for how to start: put printf() calls into your mergesort() and merge() functions that display the parameters at the start and return of each function call. That might help you figure out what's going on. Asking other people to debug your algorithm isn't going to to help you learn how to program. Better yet: use a real debugger that lets you watch variables and function calls stepwise. Using printf for debugging is a rather clumsy way of going about things. It's perfectly fine (and often constructive) to ask for help when debugging. Sometimes, if you look at a function long enough, you become blind to obvious problems. A second, or third set of eyeballs in that case is truly helpful :) I do agree that using an actual debugger would have been the next logical step, I'm just sayin ... As a sundry point I'd like to mention that you've fallen victim to error of possible integer overflow: mid=(low+hi)/2; If low and/or hi are big enough, low + hi will overflow, giving you the wrong value for mid. Instead you should do this: mid = low + (hi - low) / 2; If you used size_t for these variables, then on any real-world implementation where ptrdiff_t has the same size as size_t (and thus one fewer value bits), the overflow is not possible.
common-pile/stackexchange_filtered
Electron App and INI Files I'm currently looking int a project with Electron. I am looking at making myself a little utility app, where, when I do this normally, in such as C# or C++ I create an ini file which is in the same location of the executable so I can load it and change various settings without the need to rebuild the app, or have any complicated settings screen from within the app itself. I want to do something similar with Electron but I can't see where this is possible. I can find areas where you can read local files that are external to the electron app that are on disk but not files that are bundled with the app. I.e. I can open an ini file when the electron app loads (the ini file will always be present, there won't be a chance where it won't be, and when it comes to being bundled and installed for deployment, the ini file will be with the executable so I can modify the ini file manually and then reload the electron app which would read the ini file. Hopefully this makes sense You can use the electron and fs modules to access configuration files stored on your computer outside of the electron app. Instead of .ini files, I would suggest using .json files, they are easily parsed and managed within javascript. Here is an example to try from your rendering thread (just remove the remote to use from main thread): import electron from 'electron'; import fs from 'fs'; const data = fs.readFileSync(pathToSettingsJSON); const json = data.toString('utf8'); console.log(`settings JSON: ${json}`); settings = JSON.parse(json); You would then have a javascript object called settings that would contain properties from your JSON text file.
common-pile/stackexchange_filtered
Array, find object with value and get its indexPath I am trying to find an item in a NSMutableArray from it's value, only to find its indexPath. I have absolutely no idea of how to do this, as I am very new to programming in general. Thanks! Are you perhaps looking for - indexOfObject:? This method returns the index on which the object specified can be found in the NSArray (from which NSMutableArray inherits) on which the method is ran. Yeah, something like that. But how do I find the object? All I got is its contents.. You probably need something like this or this A top level RTFM (by linking to an object's doc's) is not helping here
common-pile/stackexchange_filtered
Post a form in a new window / inAppBrowser in Ionic (Cordova) I want to submit a checkout form to an external url, that should open a new window with the result, but I can't make my app to open it nor in a separate window, nor using the in app browser. What I've done until now is to create a directive with the form inside, and from linker function, call the submit element at some point. When I'm running in browser, this opens a new window (like I want). The problem appears when running on device, because it just REPLACES the content of my view with the new content WITHOUT OPENING an external window. So, the question is... when running on device, how can I post this form opening a new window (navigator) or in-app-browser, and show there the results? Thanks!! Show your controller. How are you invoking the IAB? I included a simplified controller, but anyway I'm not invoking the IAB with the form (that's what I don't know how to do) Well, it has been complex to figure it out, but at the end the solution is "quite" simple. I'll post it here to help any other people facing the same problem. If anyone has a more elegant solution, it will be welcomed. What I ended doing is to: Open the new window with my own template with angular and my form. In the new window controller, create a callback function in the global window object From the old window, after the loadstop event, execute that callback The posted form in the new window, redirects to the destination page (that is what I wanted to). Here's the code (Observe that I'm using a directive with the form, so I can control when to submit it, from link function, and that data is shared with the directive through a service) : angular.module('starter', ['ionic']) .constant('cartData', { redirectUrl: 'https://test.mycart.com/hpp/pay.shtml', redirectMethod: 'POST', redirectData: { 'formParam1': 'value1', 'formPara2': 'value2' } } ) .controller('InitCtrl', function($cordovaInAppBrowser, $scope, cartData) { $scope.openView = function(){ var counter = 0; if(ionic.Platform.isWebView()){ $ionicPlatform.ready(function() { //this is the cordova in app web view var ref = $cordovaInAppBrowser.open('payment.html', '_blank', {location:'yes'}); $rootScope.$on('$cordovaInAppBrowser:loadstop', function(e, event){ if(counter < 1){ //prevent the callback to be called several times $cordovaInAppBrowser.executeScript({ code: 'window.paymentCallback('+ angular.toJson(cartData) +');' }); counter++; } }); }); } }; }) //and then in payment.js window.paymentCallback = null; angular.module('payment', []) .directive('autoSubmitForm', ['$timeout', 'autoSubmitFormDelegate', function($timeout, autoSubmitFormDelegate) { return { replace: true, scope: {}, template: '<form action="{{formData.redirectUrl}}" method="{{formData.redirectMethod}}">'+ '<div ng-repeat="(key,val) in formData.redirectData">'+ '<input type="hidden" name="{{key}}" value="{{val}}" />'+ '</div>'+ '</form>', link: function($scope, element, $attrs) { autoSubmitFormDelegate.submitCallback = function(data) { $scope.formData = data; $timeout(function() { element[0].submit(); }); }; } } }]) .factory('autoSubmitFormDelegate', function(){ var delegate = {}; delegate.submitCallback = null; delegate.submitForm = function(data){ if(delegate.submitCallback){ delegate.submitCallback(data); } } return delegate; }) .controller('PaymentCtrl', function($scope, $timeout, $window, $sce, autoSubmitFormDelegate){ $window.paymentCallback = function(data){ console.log("callback called"); data.redirectUrl = $sce.trustAsResourceUrl(data.redirectUrl); $timeout(function(){ autoSubmitFormDelegate.submitForm(data); }); }; }) <link href="http://code.ionicframework.com/1.1.1/css/ionic.min.css" rel="stylesheet"> <script src="http://code.ionicframework.com/1.1.1/js/ionic.bundle.min.js"></script> <body ng-app="starter"> <ion-view view-title="Init"> <ion-content> <h1>Init</h1> <button class="button button-positive" ng-click="openView()">Open new view</button> </ion-content> </ion-view> </body> <script type="text/ng-template" id="payment.html"> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"> <meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'"> <title></title> <script src="../lib/angular/angular.min.js"></script> <script src="../js/payment.js"></script> </head> <body ng-app="payment" ng-controller="PaymentCtrl"> <auto-submit-form></auto-submit-form> </body> </html> </script> what about ionic2? Any link? Trying the same approach, but payment.html pointing to android asset folder.Therefore getting ERR_FILE_NOT_FOUND in app browser. Let me know where to place
common-pile/stackexchange_filtered
reversing the cutoff values in R using ROCR packge I am using a confusion matrix to create a ROC Curve. The problem I have is the cutoff values are revered. How to do I put them in ascending order? pred <- prediction(predictions =c(rep(5,19),rep(7,24),rep(9,40),rep(10,42)), labels = c(rep(0,18),rep(1,1),rep(0,7),rep(1,17),rep(0,4),rep(1,36),rep(0,3),rep(1,39))) perf <- performance(pred,"tpr","fpr") plot(perf,colorize=TRUE) abline(0,1,col='red') x = c(0.09375,0.21875,0.43750) y = c(0.4193548,0.8064516,0.9892473) points(x , y , col="red", pch=19) text(x , y+0.03, labels= c("9","7","5"), col="red", pch=19) predictions = c(rep(5,19),rep(7,24),rep(9,40),rep(10,42)) labels = c(rep(0,18),rep(1,1),rep(0,7),rep(1,17),rep(0,4),rep(1,36),rep(0,3),rep(1,39)) auc(predictions,labels) What do you mean by reversed? The cut-off values are 5,7,9. when it is displayed it is displaying as 9,7,5
common-pile/stackexchange_filtered
What are the best practices to validate Image and upload in ASP.Net Core/EF Core? I have found some questions like Validate Image Type but it didn't fulfill my needs. I have Model class named Movie which contains property public byte[] Image { get; set; } My View contains <form asp-action="Index" method="post" enctype="multipart/form-data"> <input asp-for="Image" type="file" id="files" class="form-control" /> <input type="submit" value="Create" class="btn btn-default" /> </form> and in controller, I am converting it to bytes and storing it in database. I want to validate it like, Files allowed .jpg, .jpeg, .png and max size of file 5Mb. [HttpPost] public async Task<IActionResult> Index(Movie Movie, List<IFormFile> Image) { foreach(var item in Image) { if (item.Length > 0) { using (var stream = new MemoryStream()) { await item.CopyToAsync(stream); Movie.Image = stream.ToArray(); } } } _applicationDbContext.Movie.Add(Movie); _applicationDbContext.SaveChanges(); return View(); } How can I validate the uploaded file ? Please don't post screenshots of your code,rather post the code itself ok, i will edit my question, thanks for feedback and why not check the filename(with extension) for known image extensions ?? and in order to check the size , take a look at this..I mean u can use FileInfo.Length and set an if condition,that's all(Note that length will return the file size in bytes,u may need to do the conversion) display it on the screen? retrieve it? @lollmbaowtfidgafgtfoohwtbs NO, Just want to validate Image only to prevent it form File Upload Vulnerability. I want to validate it like, Files allowed .jpg, .jpeg, .png and max size of file 5Mb. Every file has an extension and if it is a binary file, it has magic numbers in the header of the file that indicates what type of file it is, You can identify file type by reading the header of bytes. Check this GitHub code https://github.com/Muraad/Mime-Detective file headers reference: http://www.garykessler.net/library/file_sigs.html mime types reference: http://www.webmaster-toolkit.com/mime-types.shtml
common-pile/stackexchange_filtered
How to Add Note/field to each order product in woocommerce? does anyone have an idea how to add an editable field to each ordered product? I would like to add information, visible to the customer and administrator, for each product ordered, not the entire order. (This feature is also needed) Please provide enough code so others can better understand or reproduce the problem. if you can display note filed in your cart to particular product so you can try these. function custom_note_cart_item( $cart_item, $cart_item_key ) { $notes = isset( $cart_item['notes'] ) ? $cart_item['notes'] : ''; printf( '<div><textarea class="%s" id="cart_notes_%s" data-cart-id="%s">%s</textarea></div>', 'prefix-cart-notes', $cart_item_key, $cart_item_key, $notes ); } add_action( 'woocommerce_after_cart_item_name', 'custom_note_cart_item', 10, 2 );
common-pile/stackexchange_filtered
Checking for a particular string format in Oracle 11g In Oracle 11g, I need to check perform a check to see if the following format is true (i.e. via a regular expression): PaaaaE0% PaaaaD2% where this value is of the following format: P ( followed by any 4 alphanumeric digits) E or D (followed by atleast 1 numeric digit) As part of the 4 alphanumeric digits, if alpha then they need to be uppercase. For now, I have tried something like: REGEXP_LIKE('PWOOOE12s3','[P][:alnum:]{4}[ED][:digit:]{1}') Pls see updated question but unsure if correct and unsure how to ensure uppercase. You're pretty close: Matching a charter class should be written as [[:digit:]]. Note the outer braces for a matching list. {n} matches exactly n occurences, use + to match one or more occurences. [:upper:] matches uppercase letters, matching list [[:upper:]|[:digit:]] matches any uppercase letter or digit. I also added ^ anchor to match only from the beginning of the string. You can left it out if it doesn't fit your purpose. This should get the job done: SQL@xe> !cat so40.sql with data_ as ( select 1 id, 'PWOOOE12s3' str from dual union select 2 id, 'PwoooE12s3' str from dual ) select id, str from data_ where regexp_like(str, '^P[[:upper:]|[:digit:]]{4}[ED][[:digit:]]+') ; SQL@xe> @so40 ID STR ---------- ---------- 1 PWOOOE12s3 SQL@xe>
common-pile/stackexchange_filtered
Why do duplicate files have different checksums? I am trying to remove hundreds of duplicate .PST files from a single folder containing archived .PST files from Outlook. I've tried a couple of Duplicate Remover apps, which rely on checksums to determine equivalency, with the same result: what are clearly duplicated files have different checksums. I have been led to believe that simply having a different title shouldn't alter the checksum. What causes the different checksums? Subset of files from the .PST directory showing duplicates: 12/15/2021 09:01 AM 96,011,264 11_SonyArchiveFolderBackup Repaired (2).pst 12/15/2021 09:01 AM 96,011,264 11_SonyArchiveFolderBackup Repaired.pst 12/15/2021 09:01 AM 111,756,288 11_SonyArchiveFolderBackup.pst 12/15/2021 09:01 AM 271,360 12-4_Inbox - Copy (2).pst 12/15/2021 09:01 AM 271,360 12-4_Inbox - Copy (3).pst 12/15/2021 09:01 AM 271,360 12-4_Inbox.pst 12/15/2021 09:02 AM 21,857,280 12_SonyPersonalFolderBackup (10).pst 12/15/2021 09:02 AM 21,857,280 12_SonyPersonalFolderBackup (11).pst 12/15/2021 09:02 AM 21,857,280 12_SonyPersonalFolderBackup (12).pst 12/15/2021 09:02 AM 21,857,280 12_SonyPersonalFolderBackup (13).pst 12/15/2021 09:02 AM 21,857,280 12_SonyPersonalFolderBackup (14).pst 12/15/2021 09:02 AM 21,857,280 12_SonyPersonalFolderBackup (2).pst 12/15/2021 09:02 AM 21,857,280 12_SonyPersonalFolderBackup (3).pst 12/15/2021 09:02 AM 21,857,280 12_SonyPersonalFolderBackup (4).pst 12/15/2021 09:02 AM 21,857,280 12_SonyPersonalFolderBackup (5).pst 12/15/2021 09:02 AM 21,857,280 12_SonyPersonalFolderBackup (6).pst 12/15/2021 09:02 AM 21,857,280 12_SonyPersonalFolderBackup (7).pst 12/15/2021 09:02 AM 21,857,280 12_SonyPersonalFolderBackup (8).pst 12/15/2021 09:02 AM 21,857,280 12_SonyPersonalFolderBackup (9).pst 12/15/2021 09:02 AM 21,857,280 12_SonyPersonalFolderBackup - Copy (2).pst 12/15/2021 09:02 AM 21,857,280 12_SonyPersonalFolderBackup - Copy (3).pst 12/15/2021 09:02 AM 15,508,480 12_SonyPersonalFolderBackup Repaired (2).pst 12/15/2021 09:02 AM 15,508,480 12_SonyPersonalFolderBackup Repaired.pst 12/15/2021 09:02 AM 21,857,280 12_SonyPersonalFolderBackup.pst 12/15/2021 09:02 AM 525,312 13-6_Inbox - Copy (2).pst 12/15/2021 09:02 AM 525,312 13-6_Inbox - Copy (3).pst 12/15/2021 09:02 AM 525,312 13-6_Inbox.pst 12/15/2021 09:03 AM 145,785,856 13_DellEmailBackup (2).pst 12/15/2021 09:03 AM 145,785,856 13_DellEmailBackup (3).pst 12/15/2021 09:03 AM 145,785,856 13_DellEmailBackup (4).pst 12/15/2021 09:04 AM 145,785,856 13_DellEmailBackup (5).pst 12/15/2021 09:04 AM 145,785,856 13_DellEmailBackup - Copy (194117045).pst It seems clear to me that the archives titled "SonyPersonalFolderBackup (*).pst" are copies of the original. Note the byte counts are equal. I've not been allowed to post confirmation of the different checksums for each file but, trust me, they are different. Why is this, and what duplicate removal strategy, excluding name-based, would help me to delete them? Thanks Most likely the metadata (when it was created, etc.) is different enough to give a different checksum but not enough to change the filesize. As for duplicate removal I only would know how to do it named base. Such as using grep to find "(" and deleting the files it finds. Good luck! As nAZklX says they may be nearly identical with only some data changed. If so you will need to do some kind of binary file comparison to find out what has changed. https://stackoverflow.com/questions/8166697/tool-for-comparing-2-binary-files-in-windows and also https://superuser.com/questions/816071/how-can-i-binary-compare-two-large-files-in-windows Are you going to force me to admit I'm not using linux??? I'll see if I can get it done with Select-String in windo$e cmd line. I'll also try the COMP cmd as suggested above. thanks. Databases (like the PST file format) are often segmented into “pages”. So they can contain (as of yet) unused areas. That’s why the contents can differ substantially but the size remains the same. what are clearly duplicated files have different checksums. If they have different checksums, they are clearly not duplicated. It is possible that different files have the same checksum (in fact, since there are a finite number of checksums but an infinite number of possible files, there must be an infinite number of different files that have the same checksum). But it is not possible for identical files to have different checksums. What causes the different checksums? The cause of the checksums being different is that the files are different, not duplicates. It seems clear to me that the archives titled "SonyPersonalFolderBackup (*).pst" are copies of the original. Note the byte counts are equal. The byte counts of a file containing the string hello and a file containing the string bybye are also equal, yet clearly, the two are not identical. Why is this, and what duplicate removal strategy, excluding name-based, would help me to delete them? First, you need to define what you mean by "duplicate". Obviously, your definition of "duplicate" is different from the definition of the tool you are using (which probably uses the definition that "duplicate" means "identical"). Since you consider files to be duplicates that are clearly not identical, you need to define what you consider duplicates. If you don't know what you consider a "duplicate", then you also can't define a command which knows that. Simple - they are NOT (anymore) equal. They probably were at some time, but have been changed later. This seems very strange, unless you consider the extension - these are Outlook Mail files. Whenever Outlook opens a .pst file, it writes a time stamp and other things into it! You can easily test this by making a copy of a PST and compare them - they are equal. Now open one (or both) with Outlook, and close them - they are no longer equal. This is a very annoying behavior of Microsoft Outlook, and also the reason you cannot open any write-protected PST files with Outlook - it is so insistent of timestamping them, that it does not even display the content if they are write-protected. As a further consequence, if you have automatic backups, all PST files are considered 'changed' continuously, and result in many MB or GB senselessly being re-backuped every day. Microsoft OneDrive disallows syncing PST files for this exact reason. eol issues could also be a culprit. if you're dealing with binary files like jpgs or mp3s this shouldn't be an issue even with different file names. But any sort of text file or source code file could have crlf or lf as their line endings. Tabs may have been replaced with spaces. Any of these differences will cause different check-sums. Old question maybe, but the files can be compared without using a third party program. To verify that the files are identical, using the command window: FC /B path1 path2 Any differing bytes will be listed. If any bytes ARE different, then the checksums WILL be different. FC is DOS/Windows File Compare, the /B means do a binary compare. So...the solution to the problem stemmed from collecting the multiple backup files..the identical copies...into a common directory, thereby appending a "(*)" to each of the copies...making the file names different, and changing the checksums. Thanks. Checksums are done on the contents of a file, not metadata such as the file name. This sounds like a "feature" of whatever tool you use to create the checksums. It would be good for you to tell us what program you are using and how you are using it. Interesting. Thanks for your interest. I put a sample file in a directory, copied and pasted the copy into the same directory, which renamed the copy. I right clicked in win10 and used the CRC SHA feature from the context menu to use the "*" option to calculate all varieties of the checksum for both the original and copy. If you appended (*) to the end of one file's contents, but not another file's contents, they are now different. If you appended (*) to the end of a filename, you have an issue, because Windows does not support asterisks in filenames (they are reserved for wildcards). In the latter case, even if a Windows filename could include an asterisk, changing the filename would not change the file's checksum unless the checksum program, for some odd reason, also includes the name of the file when calculating the checksum.
common-pile/stackexchange_filtered
Mockito/PowerMock: Mock static field of class when static initialization has been suppressed I am trying to write a unit test for a method within a class, RPCProxy. This file contains some static initialization blocks for creating things related to the production environment, and for the purposes of the tests, and specifically the methods I'm trying to test, they don't make use of these production related things. Therefore, I have suppressed static initialization (without it errors are thrown because certain classes and objects cannot be found). The issue I am running into is that the class I am trying to write tests for also contains many static variables that are now not being created. The methods I am testing assume that these objects exist and, as such, when the method runs and it tries to call a method on one of these objects a NullPointerException gets thrown. What I want to know how to do is somehow mock these objects and insert them into the class somehow, so that the method uses my version, instead of the version it expects to exist which actually doesn't. For some context on what I am testing: I am trying to gets the static method RPCProxy.getInstance. This method calls a private static method called create, which returns a Proxy object. I have mocked the Proxy object, and mocked the create method to return the mocked proxy object. The only problem is that the newInstance method tries to use some of the earlier mentioned objects that do not exist. Proxy mockProxy = Mockito.mock(Proxy.class); PowerMockito.spy(RPCProxy.class); PowerMockito.doReturn(mockProxy).when(RPCProxy.class, "create", Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); assertSame(mockProxy, RPCProxy.getInstance("test12345"));
common-pile/stackexchange_filtered
Scraping experimentally measured physicochemical properties and synonyms from Chemspider in R Although the Chemspider SSOAP Web API allows one to retrieve the chemical structure of given compounds, it does not allow one to retrieve experimentally measured physicochemical properties like boiling points and listed synonyms. E.g. if you look in http://www.chemspider.com/Chemical-Structure.733.html it gives a list of Synonyms and Experimental data under Properties (you may have to register first to see this info), which I would like to retrieve in R. I got some way by doing library(httr) library(XML) csid="733" # chemspider ID of glycerin url=paste("http://www.chemspider.com/Chemical-Structure.",csid,".html",sep="") webp=GET(url) doc=htmlParse(webp,encoding="UTF-8") but then I would like to retrieve and parse the sections with chemical properties following <div class="tab-content" id="epiTab"> and <div class="tab-content" id="acdLabsTab"> and also fetch all the synonyms given after each section <p class="syn" xmlns:cs="http://www.chemspider.com" xmlns:msxsl="urn:schemas-microsoft-com:xslt"> What would be the most elegant way of doing this, e.g. using xpathSApply (as opposed to a simple strsplit / gsub job)? cheers, Tom Web scraping is always fraught. For one thing, you have no guarantee the the provider will not change their formatting at some point in the future. For another, the current formats are anything but standardized. Avoiding this was the whole point of SOAP and XML web services. Having said all that, this should get you started: library(XML) # load and parse the document csid <- "733" # chemspider ID of glycerin url <- paste0("http://www.chemspider.com/Chemical-Structure.",csid,".html") doc <- htmlTreeParse(url,useInternal=T) The data in the epi tab are actually in a text block (e.g. <pre>...</pre>), so the best we can do with XPath is to grab that text. From there you still need some kind of regex solution to parse out the parameters. The example below deals with MP, BP, and VP. # parse epiTab epiTab <- xmlValue(getNodeSet(doc,'//div[@id="epiTab"]/pre')[[1]]) epiTab <- unlist(strsplit(epiTab,"\n")) params <- c(MP="Melting Pt (deg C):", BP="Boiling Pt (deg C):", VP="VP(mm Hg,25 deg C):") prop <- sapply(params,function(x){ z <- epiTab[grep(x,epiTab,fixed=T)] r <- unlist(regexpr(": \\d+\\.*\\d+E*\\+*\\-*\\d*",z)) return(as.numeric(substr(z,r+3,r+attr(r,"match.length")-1))) }) prop # MP BP VP # 1.9440e+01 2.3065e+02 7.9800e-05 The data in the acdLabs tab is actually in an HTML table, so we can navigate to the appropriate node and use readHTMLTable(...) to put that into a dataframe. The data frame still needs some tweaking though. # parse acdLabsTab acdLabsTab <- getNodeSet(doc,'//div[@id="acdLabsTab"]/div/div')[[1]] acdLabs <- readHTMLTable(acdLabsTab) Finally, the synonyms tab is a real nightmare. There is a baseline set of synonyms, and also a "more..." link which exposes an additional (more obscure) set. The code bbelow just grabs the baseline set. # synonyms tab synNodes <- getNodeSet(doc,'//div[@id="synonymsTab"]/div/div/div/p[@class="syn"]') synonyms <- sapply(synNodes,function(x)xmlValue(getNodeSet(x,"./strong")[[1]])) synonyms # [1] "1,2,3-Propanetriol" "Bulbold" "Cristal" "Glicerol" "Glyceol" "Glycerin" "Glycerin" # [8] "glycerine" "glycerol" "Glycérol" Many thanks for that - this will be a very good start for me to get going - thx a lot!! And yes, I know, web scraping is not ideal, but due to licensing restrictions they do not offer SOAP web services to retrieve this info (to get InChIs etc the SOAP interface works great). Question to the section # synonyms tab: is there a way to not just grab the baseline set, but get all synonyms which appear with "more..."? instead of parsing ChemSpider web page it's much better and easier to use REST API: http://parts.chemspider.com/JSON.ashx So, in order to get list of synonyms, predicted and experimental properties for compound with ID 733 do this http://parts.chemspider.com/JSON.ashx?op=GetRecordsAsCompounds&csids[0]=733&serfilter=Compound[PredictedProperties|ExperimentalProperties|Synonyms] Thanks for that - as I understand it, the ACDLabs calculated properties are not available in this way though due to licensing restrictions, which is what forced me to go down the web scraping route... to answer your question you always can compare what you extracted from web page with the output of http://parts.chemspider.com/JSON.ashx?op=GetRecordsAsCompounds&csids[0]=733&serfilter=Compound[PredictedProperties] :)
common-pile/stackexchange_filtered
How find IP adress of a lost Bridge This is my network : (Yellow : Wifi and Green : Cable) My PC 3 can't obtain the IP address by DHCP because the BRIDGE 1 is LOST. I need to fix a static IP. Before, BRIDGE 1 had a static IP address <IP_ADDRESS> and it worked. I don't know how but the BRIDGE 1 lost its configuration. I already scan <IP_ADDRESS> to <IP_ADDRESS> and I don't find BRIDGE 1. How can I find BRIDGE 1?
common-pile/stackexchange_filtered
calculate path in a grid with obstacles and my analysis I want to make a program which could get the total number of paths from left top to right down spot, and there will be a few obstacles in the way. For example if I have a grid maze like below: @ + + + + + + + X X + X + + + + + + X + + X + + X + + + + $ it should tell me there are 9 paths from @ to $ (only can move right or down). Therefore I first made a little program for grid without any obstacles, here is the code: import java.util.*; import java.math.*; public class s15 { private static long nChooseK(int k, int n) { BigInteger numerator = p(k,n); BigInteger denominator = p2(k); return numerator.divide(denominator).longValue(); } private static BigInteger p2(int k) { BigInteger r = BigInteger.valueOf(1); while (k != 0) { BigInteger k1 = BigInteger.valueOf(k); r = r.multiply(k1); k--; } return r; } private static BigInteger p(int k, int n) { int p; int s = 1; BigInteger r = BigInteger.valueOf(s); for (int i = 0; i <= k-1; i++ ) { p = n - i; BigInteger p1 = BigInteger.valueOf(p); r = r.multiply(p1); } return r; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int x = sc.nextInt(); int y = sc.nextInt(); System.out.println(nChooseK(x, x+y)); } } then I first try to use this code to get how many paths 5*6 maze has if without any obstacles. Then I get 462, but I have to consider obstacles so I minus 462 with paths from each obstacles to $, and I get numbers : 21 70 6 15 10 3, surprisingly after I use 462-21-70-6-15-10-3, I get a number which is much bigger than 9, I think if I use the total paths without obstacles to minus total path obstacles blocked, it should be the total path with obstacles. What went wrong? Thx! The total number of paths is actually 126, if that's any help. It's not (x+y)Cx, but (x+y-2)C(x-1). Because you need 5 downward steps and 4 rightwards steps to navigate your 6 rows and 5 columns. Unrelated - single letter identifiers make your code quite incomprehensible. What on earth is a method called p supposed to do, for example? @DavidWallace.: There are obstaces in the path... Yes, I know that. I'm saying that his total of 462 is wrong. There are 126 paths, INCLUDING those with obstacles. @coderredoc @DavidWallace.: oh ok.. 9 choose 4 The total path obstacles blocked is not that easy to calculate. It should be the number of paths that starts from @, moves down or right, ends at $, and passed at least one obstacle. For this problem, there are two algorithms which aim to different data scales. 1) Inclusion–exclusion principle The total paths obstacle blocked = (The total paths that pass any one obstacle) - (The total paths that pass any two obstacles) + (The total paths that pass any three obstacles) - ... The total paths that pass any K obstacles can only be calculated using enumeration. That is, take all subsets of the whole obstacles with exactly K elements and count the paths that pass them. Given K obstacles, if there are any two obstacles forms a (left, down) -- (right, top) pair, there would be no paths that pass these obstacles. Otherwise, we can sort them from (left, top) to (right, down) and the count would be (the total path from @ to obstacle 1) * (the total path from obstacle 1 to obstacle 2) * ... * (the total path from obstacle K to $). Finally, the total path from a to b can be solved by nChooseK. What a long journal! Assuming there are S obstacles at all, the time complexity of this algorithm would be O(S*2^S). 2) Dynamic Programming This is much easier if you've already known DP. If not, I would suggest you google and learn it first. In short, the formula is f[0][0] = 1 if cell (i, j) is an obstacle f[i][j] = 0 else f[0][j] = f[0][j - 1] f[i][0] = f[i - 1][0] f[i][j] = f[i - 1][j] + f[i][j - 1] Answer = f[N - 1][M - 1] where f[i][j] represents the total paths that starts from @, passes no obstacle and ends at cell (i, j), and (N, M) is the dimension of the board. The time complexity is O(NM). Thank you very much, now I know what this problem is doing is try to teach me dynamic programming, I will learn it first! dp[i][j]=dp[i-1][j] + dp[i][j-1]...if g[i-1][j] and g[i][j-1] is free. The points neighbor to start point will be of length 1( ofc valid points) Okay so the person who downvoted..thanks to him. So here there is 3 things to remember We can only move in down or right. So we can come to [i,j] point from two points if they are at all free. Those will be [i-1,j] or [i,j-1]. The number of paths to reacj [i,j] will be equal to sum of the ways to reach [i-1,j] and [i,j-1] (if free). And we need to consider few edge case like [0,y] or [x,0]. So dp[i][j]= dp[i-1][j]+dp[i][j-1] if i>=1 & j>=1 dp[i][j-1] if i=0 & j>=1 dp[i-1][j] if i>=1 & j =0 1 if i=0 & j =0 0 if x[i][j] is obstacle Answer will be dp[row-1][col-1]. Time complexity: O(row*col) Space complexity: O( row*col) dp array will be 1 1 1 1 1 1 2 3 0 0 1 0 3 3 3 1 1 4 0 3 1 0 4 4 0 1 1 5 9 9 @Tony Chen.: Check my answer. You asked me to check your answer. Did you test it yourself? It does NOT return 9 for this particular grid, which it should. @DavidWallace.: Now it is ok...sorry for hurried answer. Yes, it's now effectively identical to the second half of Mo Tao's answer. @DavidWallace.: Hey I didn't copy it..I answered the main idea even before Mo Tao answered...if you feel like I am cheating either downvote or ask me to delete..whichever you feel to be right. I never accused you of copying it. I know perfectly well that you didn't. So if you feel your answer will be useful to OP then by all means leave it there. For the reference, If you have very few obstacle, Aside from the Inclusion-Exclusion method above, It's possible to sort obstacles by its distance from start so that all obstacle is not contained in any previous obstacle. Now, consider that we can partition every path that passed some obstacle by the first obstacle it passed. We can then calculate for every obstacle, how many path that has this obstacle as first obstacle. Once we know that, Just sum them up and we got the answer. Time complexity: O(k^2) where k is number of obstacle
common-pile/stackexchange_filtered
Starting Google Chrome from the command line with a blank page How can I start Google Chrome with a blank page from the command line (chrome.exe)? check the default load page and make blank then use chrome.exe to launch. I'd like to point you to the [FAQ#etiquette] where it says, > Civility is required at all times; rudeness will not be tolerated. This is your last warning. Don't be rude against community members. correct, but downvoting a question without a reason... isn't civil @user698585 people may have their reasons. Most popular reason is "does not show research effort". And your question might fall into the catogory a google search could have solved on its own. Walter: The question has been asked precisely because a google search didn't yield satisfactory results and by the way the stackexchange administration itself urges users to clearly comment on their downvote reason. From the command line, simply type: chrome.exe -homepage "about:blank"
common-pile/stackexchange_filtered
Mac OS Modal Dialog Offscreen Blocking Google Chrome? I have a MacBook Pro that I take from work to my house. I rarely open the lid and almost always hook up to an external monitor. I frequently find, and I'm unable to find a pattern to consistently reproduce, that I will plug into a monitor and power source, have the MacBook wake up and then discover that several menu options in Google Chrome (where I do about 75% of my work) are grayed out. Right-click context menus are largely grayed out and in particular the Quit Google Chrome item under the Chrome menu is as well. This means I frequently need to force quit Chrome to shut it down. Clicking Xs to close tabs yields a beep indicating that the UI is in some way blocked, but a CMD+W will successfully close a tab. Occasionally, I can see the dialog in question flitting on and off screen, fading as it moves, when using Expose, but I cannot get it to relocate to the viewable window area. I suspect the modal dialog in question is related to a finicky AJAX app that feels compelled to pop up JS alert('...') dialogs when it can't connect to its server. Unfortunately, I have no control over that particular web app, and it's one I use regularly. As I do work predominantly in my browser, having to force quit and losing 20 (or more) tabs is really frustrating. I've found some Apple Script (or whatever the Mac OS native scripting language is called) scripts people have written to recenter errant windows, but this does not seem to work on modal dialogs. What are my options for resolving this issue? In 2018 this is still a problem. Modal dialogs are bad design. Usually I get lucky and can find the edge of the modal hanging around the edge of the screen. Something that helps when killing Chrome is the Tabs Outliner plugin which helps me to recover the tabs that died.
common-pile/stackexchange_filtered
Checking a hash table if a key exists, otherwise default to something that exists and return that value I have the following function which works great, but I would like to make sure that if the supplied zone does not exist, that it uses default zone key. module.exports = (zone, key) => { const zones = { default: require('./default'), northeast: require('./northeast'), centralCoast: require('./centralCoast') }; return zones[zone][key]; } Is there a cooler way to do this straight in the return statement? Right now, I am just using a conditional check to check if I get anything but undefined and return that.. How can I check that the zone is one of the zones like northeast, centralCoast, etc but if someone passes western it would just return values for default I don't fully understand your code, you're returning locales, but your object is declared as zones. and then, what is the key parameter?? sorry each of the these are just maps, so for example if you require this particular function, call it example, and execute like example('northeast', 'shipping')['some-value'] then it will return that value. I assume locales should be the same object as zones? You can use a simple ternary operator to achieve conditional logic in the return statement. You can also use an arrow function to omit having to specify explicit return: module.exports = (zone, key) => zones[zone] ? zones[zone][key] : zones.default[key]; I suggest to also move some of the static (non-changing code) outside of the function so it's not unnecessarily executed on each function call: // move constants outside of the function because there's no need to recreate them on each function call const zoneNames = ['default', 'northeast', 'centralCoast']; // import the zones dynamically // this way, adding new zones requires only adding a string to the array above const zones = zoneNames.reduce((zones, zoneName) => { zones[zoneName] = require(zoneName); return zones; }, {}); module.exports = (zone, key) => zones[zone] ? zones[zone][key] : zones.default[key];
common-pile/stackexchange_filtered
UIView to another View in objective C when i goto the next view support in UIView based application, i have to goto secondView * = [[secondView alloc]initWithNibName:@"secondView" bundle:[NSBundle mainBundle]]; [UIView beginAnimations:@"ani" context:nil]; [UIView setAnimationDuration:0.9]; [UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:NO]; [UIView commitAnimations]; [self.view addSubview:secondView.view]; my question is that i can't release the secondView because my object are remove on the same view.. if i can't and goto the second view the how and when to release the secondView object and in which view .. because i also have to come back from the secondView to the firstView like that.. i write the back code: [self.View removefromsuperview]; // means this code is written on second View backbutton then its goto the firstView.. I want to know that when i release the secondView object which i create the in the firstView... i don't use autorealease because its very bad ... i also think the one solution that could i release the secondView object in the firstView dealloc Class .. please help me.. thanks. It's a little unclear what you are asking exactly... i am asking when to release the secondView object which i create in the first View ... thats all .. simply .. and what is the best possibilities .. !! Your use of initWithNibName and .view suggest that secondView is an instance of a UIViewController subclass. If that's the case then you should not be adding one UIViewController's view as a subview of another UIViewController's view. Doing so is abusing UIViewControllers and will result in unexpected behavior in your app. If you want to manage transitions between views you should either use one of Apple's provided container view controllers to manage multiple UIViewControllers or swap between subviews of a single UIViewController's view. Either way your controller could be released by whichever parent controller is managing the transition between views. For example if you were using a UINavigationController it could release a controller when it is popped off the navigation stack. If you wrote your own UIViewController to manage multiple views, each of which might have a non-UIViewController controller, then you could release a view and it's controller from that parent view controller when the sub view is no longer needed. Let parent objects manage their children. i am not understanding your answer too much .. :(
common-pile/stackexchange_filtered
format 24-hour query sqlite3 I have this data frame. index id created_at 0<PHONE_NUMBER>379910149 Sat Dec 14 18:10:39 +0000 2019 1<PHONE_NUMBER>091813888 Sat Dec 14 18:10:37 +0000 2019 2<PHONE_NUMBER>988711936 Sat Dec 14 18:10:37 +0000 2019` i need extract the hour in the format %H:%M:%S This is my code query = ''' SELECT id as "id tweet", strftime('%H:%M:%S', created_at) as "hour" FROM tab_created ''' But, the output is index id tweet hour 0<PHONE_NUMBER>379910149 none 1<PHONE_NUMBER>091813888 none 2<PHONE_NUMBER>988711936 none i need something like index id tweet hour 0<PHONE_NUMBER>379910149 18:10:39 1<PHONE_NUMBER>091813888 18:10:37 2<PHONE_NUMBER>988711936 18:10:37 Thanks for help me. Read this post, it might help you The function strftime() recognizes dates only in the format YYYY-MM-DD HH:MM:SS and similar. So your format is not applicable to strftime(). What you can do, if the format is always like Sat Dec 14 18:10:39 +0000 2019 is use the function substr(): SELECT id as "id tweet", substr(created_at, 12, 8) as "hour" FROM tab_created See the demo. Results: | id tweet | hour | | ------------------- | -------- | |<PHONE_NUMBER>379910149 | 18:10:39 | |<PHONE_NUMBER>091813888 | 18:10:37 | |<PHONE_NUMBER>988711936 | 18:10:37 |
common-pile/stackexchange_filtered
When trying to deploy a smart contract, I keep getting `Error HH100: Network ropsten doesn't exist` -- how do I resolve? I'm running through these docs on deploying an NFT and I keep getting the error: Error HH100: Network ropsten doesn't exist The command I'm using can be found at step 16: npx hardhat --network ropsten run scripts/deploy.js This is what my deploy.js file looks like: async function main() { const MyNFT = await ethers.getContractFactory("MyNFT") // Start deployment, returning a promise that resolves to a contract object const myNFT = await MyNFT.deploy() await myNFT.deployed() console.log("Contract deployed to address:", myNFT.address) } And this is what my hardhat.config.js file looks like: /** * @type import('hardhat/config').HardhatUserConfig */ require('dotenv').config(); require("@nomiclabs/hardhat-ethers"); const { API_URL, PRIVATE_KEY } = process.env; module.exports = { solidity: "0.8.1", defaultNetwork: "rinkeby", networks: { hardhat: {}, rinkeby: { url: API_URL, accounts: [`0x${PRIVATE_KEY}`] } }, } How do I fix this error? This hardhat error happens when you are trying to interact with a network that is not defined in the config file. Specifically, because you are using the --network ropsten flag, the config file expects networks.ropsten to be defined. However, you only have networks.rinkeby defined. I'd recommend adding a definition for networks.ropsten (and making sure to use the appropriate API_URL for ropsten). For example: /** * @type import('hardhat/config').HardhatUserConfig */ require('dotenv').config(); require("@nomiclabs/hardhat-ethers"); const { RINKEBY_API_URL, ROPSTEN_API_URL, PRIVATE_KEY } = process.env; module.exports = { solidity: "0.8.1", defaultNetwork: "rinkeby", networks: { hardhat: {}, rinkeby: { url: RINKEBY_API_URL, accounts: [`0x${PRIVATE_KEY}`] }, ropsten: { url: ROPSTEN_API_URL, accounts: [`0x${PRIVATE_KEY}`] }, }, } With this config, if you run: npx hardhat --network ropsten run scripts/deploy.js it should work! P.S. Also make sure you have testnet ether: https://www.rinkebyfaucet.com/ https://goerlifaucet.com/ https://faucet.dimensions.network/ Had network defined instead of networks! Thanks for the fix :) those typos can be annoying in hardhat configs :) happy to help!
common-pile/stackexchange_filtered
if css(background-position) jquery conditional statement I am animating background image on my website by various amount of pixels depending on current position. I created an 'if' statement but it completely ignores the if ($("#bg").css("background-position") part, and is animating no matter what. Animation is working fine, even in Firefox, the problem is that the second condition is ignored and it always move by 670px. If i put into conditions other css value, like height for example, then it works. $(function () { if ($("#bg").css("background-position") == "0px 0px") { $("#arrows .right").click(function(){ $("#bg").animate({backgroundPosition:"-=670 0px"}, 4000); }); } else if ($("#bg").css("background-position") == "-670px 0px") { $("#arrows .right").click(function(){ $("#bg").animate({backgroundPosition:"-=1000 0px"}, 4000); }); }; }); is background-position not working in a conditional statement at all? I also try to change link depending on background position, this is completely ignored: $(function () { if ($("#bg").css("background-position") == "-670px 0px") { $("#cafe a").attr("href", "http://mywebsite.com/about-us/") }; }); Log $("#bg").css("background-position") to learn what happens. Thank you for reply. It shows: 0px 0px, even if I click to animate and it moves to 670px. so this is the reason why it always moves by 670, it means then that it actually takes into account the condition, but doesn't 'write' new value into css? I'm confused. Could you make a jsfiddle example? Me too :) I have created it here: http://jsfiddle.net/kXQ99/7/ but it now doesn't work here, can't see why Anyway, so the thing is that after seeing log, background-position is always 0,0 even when it animates to different x value, so I can't determine the next position and animate it further by another set of x values (new background position always depends on previous position) - so maybe there is easier way of achieveing that? I haven't done much background animating, so I'm not really sure if this is still an issue you need to solve with a plugin, but that is what I did: http://jsfiddle.net/kXQ99/14/ I added the plugin at the top, because otherwise I would've had to upload and link it externally. Your code is at the bottom -- Oh and I tidied up your code a bit... Thanks, this is great! it works exactly how I wanted. I am actually using this plugin already on my site, forgot to add it to fiddler :) Now I need to figure out how to add extra button to move left and right to different points of interest. Please add it as an answer so I can add you points (if this how it works here?). With the code in that jsfiddle I liked, you can make another link so that you have <a class="arrows left"></a> <a class="arrows right"></a>. Then change the id to class in your javascript. Inside the click event you can put an if statement and ask: if ( $(this).hasClass('left') ) { /* Left arrow was clicked */ } else { /* Right arrow must have been clicked, since there are only two arrows */ } Fantastic. How can I give you some points for the answer? Is it possible to continuously animate that background, so when it reaches last position on the right - it then goes to the first point, but not by scrolling back to the left, but by still moving to the right? (I thought of repeating the bg but then I will have to have endless calculations of x positions....). Sorry for confusing it even more :) Here's something I wrote a while back. Something like this: http://jsfiddle.net/lollero/J25dk/1 ? It works by animating the container by width of one image and when the animation ends it moves the first image to the last place, resets position to 0 and then loops that indefinitely. -- I can make an answer later, which you can choose as the right answer or just give a plus. I just wanted to mention these two things, since I never really tried to properly answer the question. I just kinda got around it. 1. The issue with your jsfiddle was that, well you forgot to add jquery in it... and it did have actual code issue as well. You expected value -670px 0px after the second click, but it actually gave this value -670px 50%. The first animation, I guess, switched 0 to 50% even though you didn't even try to animate y. I'm not sure if it even should be analyzed, since I guess jquery doesn't natively support background position animation. 2. You said you had that plugin already in your website and I think the issue with that was that the plugin doesn't understand singular numerical value with backgroundPosition. I took your original jsfiddle, added the plugin and added second value to the animate and it started working. jsfiddle of that The jsfiddle I gave you in the comments is basically identical to what I linked above, except it's just a little more compact. Jsfiddle of the compact working code Here's the compact working code with comments: /* http://keith-wood.name/backgroundPos.html Background position animation for jQuery v1.1.1. Written by Keith Wood (kbwood{at}iinet.com.au) November 2010. Available under the MIT (https://github.com/jquery/jquery/blob/master/MIT-LICENSE.txt) license. Please attribute the author if you use it. */ (function($){var g=!!$.Tween;if(g){$.Tween.propHooks['backgroundPosition']={get:function(a){return parseBackgroundPosition($(a.elem).css(a.prop))},set:setBackgroundPosition}}else{$.fx.step['backgroundPosition']=setBackgroundPosition};function parseBackgroundPosition(c){var d=(c||'').split(/ /);var e={center:'50%',left:'0%',right:'100%',top:'0%',bottom:'100%'};var f=function(a){var b=(e[d[a]]||d[a]||'50%').match(/^([+-]=)?([+-]?\d+(\.\d*)?)(.*)$/);d[a]=[b[1],parseFloat(b[2]),b[4]||'px']};if(d.length==1&&$.inArray(d[0],['top','bottom'])>-1){d[1]=d[0];d[0]='50%'}f(0);f(1);return d}function setBackgroundPosition(a){if(!a.set){initBackgroundPosition(a)}$(a.elem).css('background-position',((a.pos*(a.end[0][1]-a.start[0][1])+a.start[0][1])+a.end[0][2])+' '+((a.pos*(a.end[1][1]-a.start[1][1])+a.start[1][1])+a.end[1][2]))}function initBackgroundPosition(a){a.start=parseBackgroundPosition($(a.elem).css('backgroundPosition'));a.end=parseBackgroundPosition(a.end);for(var i=0;i<a.end.length;i++){if(a.end[i][0]){a.end[i][1]=a.start[i][1]+(a.end[i][0]=='-='?-1:+1)*a.end[i][1]}}a.set=true}})(jQuery); // On document ready $(function() { // When #arrows element is clicked... $("#arrows").on("click", function () { // Get the background position. var bgPos = $("#bg").css("background-position"), // These two are ternary if statements.. // In human language these would be: // if bgPos is equal to '0px 0px', use "-=670px 0px" OR.... // if bgPos is equal to '-670px 0px', use "-=1000px 0px" newPos = ( bgPos === '0px 0px' ) && "-=670px 0px" || ( bgPos === '-670px 0px' ) && "-=1000px 0px"; // Console logs that help keep track of what is happening. console.log( 'Background position: ' + bgPos ); console.log( 'If statement #1: ' + ( bgPos == '0px 0px' ) ); console.log( 'If statement #2: ' + ( bgPos == '-670px 0px' ) ); // Animate #bg... $("#bg").animate({ backgroundPosition: newPos }, 4000); }); });
common-pile/stackexchange_filtered
how to import "process" package? I'm using "eye tracking" Git code, and my pyChram can't import "process" package. import process I tried to import process through pip (by cmd). it failed and output ERROR: Could not find a version that satisfies the requirement process (from versions: none) ERROR: No matching distribution found for process Also, I tried to look into https://github.com/stepacool/Eye-Tracker but no information about it. process.py is a module in the repository that you link, import process should just import that module. You are probably trying to run main.py from a different path, run it from the same path and it should work. In context of OP he probably means process.py in the root directory of the Eye-Tracker package. @jdehesa that's it! but could you advise me how to make the main run from that same path? how to choose which path to run my main? @Omri How are you running the program? As the repo suggest, you should open a prompt, navigate to the directory and run python main.py. If you are using a script or a shortcut or something like that to run it then you would need to configure that.
common-pile/stackexchange_filtered
mariadb 5.5 innodb keeps opening files up to 200k until system hangs completely Mariadb 5.5 is installed on CentOS and serves a database in the total volume of around 40GBs (as measured per database files on a disk) and 506 tables. This database is being queried by php-fpm, and the issue is that at some point, when traffic increases, the number of open files opened by mysqld process (as per lsof states) grows up to around 200k and system hangs (specifically web requests ar being extremely slow, 5mins for TTFB). The server itself is should have enough capacity (Supermicro; X10DRH with 125gb of RAM and SSD) to be able to perform quickly on such a modest load. Examination of lsof output shows that mysqld process keeps open tables on and where: [root@mail proc]# lsof | wc -l 95592 most of them are open tables: [root@mail proc]# lsof | grep .ibd | wc -l 57331 before that, lsof showed very big qty of /[aio] and putting innodb_use_native_aio=0 improved the situation a bit mysql_slow_log does not show queries that are running longer than 5s, | Innodb_mem_total |<PHONE_NUMBER>0 my MySQL config is: [mysqld] datadir=/var/lib/mysql socket=/var/lib/mysql/mysql.sock symbolic-links=0 innodb_file_per_table = 1 innodb_buffer_pool_size = 1G innodb_io_capacity = 2000 innodb_read_io_threads = 64 innodb_thread_concurrency = 0 innodb_write_io_threads = 64 innodb_use_native_aio=0 skip-name-resolve=1 max_heap_table_size=256M tmp_table_size=256M slow-query-log=1 long_query_time=1 for some tables mysql.log shows some errors on startup: 191205 7:21:25 InnoDB: Error: trying to open a table, but could not InnoDB: open the tablespace file './staging/yotpo_rich_snippets.ibd'! but I'm not sure is that might be a reason for low performance. also, database data files are located in /home/ partition, which is : /dev/md2 /home ext4 grpquota,usrquota,data=ordered,relatime,rw 0 2 any hint on where to dig would be highly appreciated. Sounds like connections are not being closed. Post 15 seconds of your general log for analysis, please. Several possibilities: Some queries are taking a long time (and hanging onto files (that is, tables) meanwhile). -- Look for slow queries; let's work on speeding them up. You have the slowlog turned on; use pt-query-digest to identify the 'worst' queries. The APP uses the "EAV" model, which joins lots of tables. -- If this is the case, let's discuss that. The web server allows a huge number of connections. If it is allowing "too many", then will just stumble over each other. "5mins for TTFB" is a clue of this. -- Throttle connections at the web server layer. Not effectively using RAM. You have 125GB of RAM, yet innodb_buffer_pool_size is only 1G. -- Change that to 80G. Meanwhile, delete this Q&A and stick with the better site: dba.stackexchange.com .
common-pile/stackexchange_filtered
Rationals in [0,1] are $F_{\sigma}$? I have the following problem that I think I have worked out. Let $A$ be the set of rational numbers in $[0,1]$. Is $A$ an $F_{\sigma}$ set? My Attempt: Yes, $A$ is an $F_{\sigma}$ set. We recall that an $F_{\sigma}$ set is one which may be expressed as the countable union of closed sets. Since the set of rationals $\mathbb{Q}$ are countable, so too is the set $A$. Hence, we may enumerate it as $A=\{q_{k}\}_{k=1}^{\infty}$. Now, each singleton set $\{q_{k}\}$ is closed in $\mathbb{R}$ (with the standard topology), since its complement $\{q_{k}\}^{c}=(-\infty,q_{k})\cup(q_{k},\infty)$ is open. Thus, we have $A=\bigcup_{k=1}^{\infty}\{q_{k}\}$, so $A$ is indeed an $F_{\sigma}$ set. My concerns: I think my above argument is okay, but I am shaky on one part. Does it matter if I consider each $\{q_{k}\}$ as closed in $\mathbb{R}$, or do I need to show explicitly that they are closed in $[0,1]$? Thanks in advance for any help! Yes it is a set. What you did is sufficient. Good job!
common-pile/stackexchange_filtered
I need to access/edit the HTML code of page Templates which are written in PHP in wordpress I'm getting confused on how to get the HTML code when the website is already made in page templates. In page templates there is all PHP written which is fetching HTML by itself no html is shown there. I need to get my hands on HTML of the page. I wordpress they are using small small html snippet in different different php file. You not edit whole html in one place. Ty for your response!. I need to change 1 picture only but HTML is not showing up in the template's php file. The PHP file getting header,footer and the content of html from where? You can not edit a single HTML page. By cons you can customize your themes, modifying PHP files (containing your HTML) that can expand only with a single HTML page. To edit theme files: Appearance -> Editor I want to edit the template which is used in the page not the whole page. I know where my template is but it is in php, the designing the pictures are not there in that php file nor any other file is fetching there. The thing is i need to customise that template. BTW thanks for your comment. Find the name of the image tag you want to edit. Then access to your site in FTP and search among all the files, it should help you. Your all js, html and also php are in .php files. There's no way you want only to see/edit html only. If you want to edit specific html, first check your element class/id with Inspector by pressing F12 or CTRL+Shift+I and then go looking the element class/id on the php files by Appearance > Editor. For example, you want edit your picture element class/id on the homepage, it should be in index.php (note that: some developer theme have different way), if on the content page then the element is around single.php and content.php files You cannot find only HTML code inside Wordpress theme. Wordpress is based on PHP and all are written by PHP. If you have to customize the template, you can learn How to create a custom template page? And also this is the template documentation Wordpress Pages template Doc
common-pile/stackexchange_filtered
Retrieving live value from range input to use in another function I know this is something really simple but I'm having trouble understanding how to return a live value from a range input slider and how to use that value in another function. HTML <input type="range" min="0" max="10" step="1" value="0"> <div class="value">0</div> JS var elem = document.querySelector('input[type="range"]'); var rangeValue = function(){ var newValue = elem.value; var target = document.querySelector('.value'); target.innerHTML = newValue; return newValue; } function test(){ console.log (newValue); } elem.addEventListener("input", rangeValue); I have been trying to retrieve the value with both global variables and return but keep running into problems. I would appreciate if anyone could explain how this can be done using both methods. Thank you in advance What kind of "problems", can you post what results you are getting and what the expected results should be? Your code works fine... What you mean by running into problems I am not seeing any values from 'newValue' appear in the console @NewbCake Of course not, you don't call the test() function anywhere. And your return newValue; is useless since there is nothing that can make use of it as it is the listeners callback function. I think this is what you want: var elem = document.querySelector('input[type="range"]'); var rangeValue = function(){ var newValue = elem.value; var target = document.querySelector('.value'); target.innerHTML = newValue; test(newValue); } function test(newValue){ console.log (newValue); } elem.addEventListener("input", rangeValue); Test here: https://jsfiddle.net/k05qm2v5/ Also, using querySelector('input[type="range"]') is not the best idea. You should give it a name or ID and get it like: var elem = document.getElementById('miRange'); HTML: <input id="myRange" type="range" min="0" max="10" step="1" value="0"> <div class="value">0</div> Ah okay that works. So you are calling the "test' function which that value is going to be used inside the first function? What happens if the value was going to be used in other functions? is there no need to use return or make a global variable? Then just declare a variable at the top of the file, lets say var globalVariable = null; Then inside the rangeValue function you just put globalVariable = newVarible; Keep in mind w3schools says: Do NOT create global variables unless you intend to. Your global variables (or functions) can overwrite window variables (or functions). Any function, including the window object, can overwrite your global variables and functions. So what I am doing wrong in something like this – https://codepen.io/NewbCake/pen/rvYoay?editors=1011 You have one extra ")" here: $("#fontSize").css({'font-size': newValue + 'px'}); after newValue
common-pile/stackexchange_filtered
Can particle physics be represented as an algebra? Possibly the most useful thing anyone could tell me about particle physics: Naively, one could try and make an algebra by enumerating all the types of particles and defining equivalence relationships (some rules), for example Objects: object type 1: photon object type 2: electron object type 3 ... object type n Rules: rule 1: a photon is equivalent to an electron and a positron rule 2: a proton is equivalent to three quarks rule .... rule n Then one could study the properties of these relationships as a mathematical structure containing objects that represent particles and rules that define equivalence - i.e. as an algebra. I assume such an algebra would be, if formulated correctly, represented by Feynman diagrams (for some particles at least). Does such an algebra have a name? Is there more than one? Is this at all connected to the idea behind stating that the standard model is U(1) x SU(2) x SU(3)? By an algebra I understand a closed and consistent collection of mathematical objects and relationships. Thanks for trying to understand what I'm asking, with your input I can aim to make this more comprehensible. So I guess I'm looking for a formal structure which reflects particle reactions which is abstracted away from spatial, temporal and energetic considerations as far as is possible (is it at all possible?). I have trouble understanding what you're saying here. This site is geared for practical, answerable questions based on actual problems that you face. Combined with a typo in both the title and the standard model gauge group ⇒ -1. If I understand correctly, the OP is trying to partition all known particles into two sets and then trying to establish some kind of (homo,iso) morphism between them based on known physics. I am not sure what the point of this exercise is? I don't think any question, however ill formulated deserves to be shot down. +1 @Antillar: Maybe I was a bit harsh... after the latest edit it does not annoy me so much! (Reversed my -1) Lucas: What you're saying actually reminds me a bit of bootstrap models. But it is only indirectly related to the standard model gauge group. In that your equivalences would have to include the group representation aspects and more. Simon: You got me looking at S-matrices, they seem pretty close to what I was thinking of, I need to look into it more to tell. yes, bootstrapping seems to be intimately connected to what I was asking. Although I wasn't suggesting the validity of a such a theory would be by it's consistency alone, which seems like what the bootstrappers thought. I think the answer lies in properties of S-matricies, any good introductions? What you want is an algebraic relation on particles which tells you which ones are allowed to turn into which other ones. These algebraic relations exist, and they are the conservation laws. The conservation laws come in two types--- discrete and continuous. The full list of exact conservation laws is known, and the exact ones are these: Energy/Momentum Angular momentum Electric charge CPT In addition, there is one more conserved quantity, which is algebraically more complicated Strong color charge This one is only applicable at short distances, and it tells you which collections of quarks and gluons can turn into which other collections of quarks and gluons. All objects are neutral at long distances. In addition to these laws, there are two more nearly exact conservation laws: Generational lepton number (number of electrons+neutrinos of each generation) Baryon number (the number of end-stable protons plus neutrons) There are further conservation laws which are not at all exact, but are preserved by the electromagnetic and strong interactions at low energies. These are parity, and charge conjugation. All processes which obey the exact conservation laws are allowed in principle, although they might have vanishingly small probability amplitude. "These are parity, and charge conservation" I think you meant "charge conjugation". So I would have a collection of objects defined by a set of quantum numbers and equivalences that are conservation laws. The non-exact ones are from vanishing small probabilities? @Lucas--- the "algebraic objects" you are talking about are the conserved quantities--- the sum of the charges for example. I don't know what you mean by "equivalences", you don't mean "equivalent", because a photon is not the same as an electron/positron. So you mean "can turn into".
common-pile/stackexchange_filtered
Pull info from a Microsoft Access database into the php and apache web environment? We have a client who uses a custom build client management system that runs on Microsoft access. The website we have needs to pull some client info from that database. But how do we pull info from a Microsoft Access database into the php and apache web environment? Is there an odbc connector somewhere that could do the Job? Which database are you using on the Web end? Is this a one time migration or will it be done on a regular basis e.g. daily/weekly/monthly upload? "Here is how to create an ODBC connection to a MS Access Database" -- http://www.w3schools.com/php/php_db_odbc.asp
common-pile/stackexchange_filtered
When splitting text lines after a full stop, how do I specify when NOT to split like after the title 'Dr.'? #!/usr/bin/python #Opening the file myFile=open ('Text File.txt', 'r') #Printing the files original text first for line in myFile.readlines(): print line #Splitting the text varLine = line splitLine = varLine.split (". ") #Printing the edited text print splitLine #Closing the file myFile.close() When opening a .txt file in a Python program, I want the output of the text to be formatted like a sentence i.e. after a full stop is shown a new line is generated. That is what I have achieved so far, however I do not know how to prevent this happening when full stops are used not at the end of a sentence such as with things like 'Dr.', or 'i.e.' etc. Best way, if you control the input, is to use two spaces at the end of a sentence (like people should, IMHO), then use split on '. ' so you don't touch the Dr. or i.e. If you don't control the input... I'm not sure this is really Pythonic, but here's one way you could do it: use a placeholder to identify all locations where you want to save the period. Below, I assume 'XYZ' never shows up in my text. You can make it as complex as you like, and it will be better the more complex it is (less likely to run into it that way). sentence = "Hello, Dr. Brown. Nice to meet you. I'm Bob." targets = ['Dr.', 'i.e.', 'etc.'] replacements = [t.replace('.', placeholder) for t in targets] # replacements now looks like: ['DrXYZ', 'iXYZeXYZ', 'etcXYZ'] for i in range(len(targets)): sentence = sentence.replace(targets[i], replacements[i]) # sentence now looks like: "Hello, DrXYZ Brown. Nice to meet you. I'm Bob." output = sentence.split('. ') # output now looks like: ['Hello, DrXYZ Brown', ' Nice to meet you', " I'm Bob."] output = [o.replace(placeholder, '.') for o in output] print(output) >>> ['Hello, Dr. Brown', ' Nice to meet you', " I'm Bob."] Use the in keyword to check. '.' in "Dr." # True '.' in "Bob" # False Why was this downvoted Probably because it doesn't answer the question above. If line is 'Dr. Bob', splitLine will be ['Dr', 'Bob'].
common-pile/stackexchange_filtered
Integrating Sine Wave shifted up by 1 When I integrate sine waves with 1Hz in Matlab, why does the result shift by 1? The integral block's initial value is 0. I would like to know why this happens and the correct way to solve it. The solution I came up with is to change the initial value to -1 and this solved the issue but I'm not sure about the consequences of changing the initial value. It seems Matlab assumes the integration constant is 2. You're working with machines here! This one does not know the simplified paradigma(integral sin = -cos) we learn in maths! ;) Simulink here just numerically integrates the sine. And it just starts from zero as you set. If you imagine the integration as area below the sine-curve, you can easily follow, what it does: The integral starts from zero and increases until x=pi, with a maximum slope where the sine is at its maximum (x=pi/2). Then, the sine changes to negative values, so the integral decreases again until it reaches 0 at x=2pi, where the two halfes of the sine just equalise. Just as to expect. Or mathematically said: The general antiderivative of sin(x) is -cos(x) + A. As the initial value of the integral is set to zero, you get the constraint of -cos(0) + A = 0, which comes to A=1. And y = -cos(x) + 1 is just the blue curve you see. what do you mean by 'integrate sine waves with 1Hz'? with 1/s you are integrating the input. If you multiply instead you differentiate. Review Laplace Transform basics, for instance here https://en.wikipedia.org/wiki/Laplace_transform
common-pile/stackexchange_filtered
The exhaust measurements don't match our predictions at all - the velocity keeps increasing even as the nozzle expands. That's exactly what should happen in supersonic conditions. Most people expect the opposite because they think like subsonic flow. But that defies basic intuition - when a pipe gets wider, flow should slow down, not speed up. Only if you ignore compressibility effects. The key insight comes from mass conservation: density times velocity times area stays constant. Right, so $\rho VA = constant$. When we differentiate that relationship, we get the change in density over density, plus change in velocity over velocity, plus change in area over area, all summing to zero. In subsonic flow, density barely changes, so when area increases, velocity must decrease to maintain the balance. But supersonic flow changes everything. The gas becomes highly compressible above Mach one. As the nozzle widens and area increases, the density actually drops faster than the area grows. So to keep the mass flow constant, velocity has to increase dramatically to compensate for that density loss. Exactly. The throat is where the magic happens - that's where the flow hits Mach one, becomes sonic. Everything upstream is subsonic, everything downstream goes supersonic. The pressure and temperature also drop as we move past the throat, which affects the local speed of sound and amplifies the acceleration effect. That's why our engine intake design has been backwards. We've been treating the supersonic section like it's subsonic flow. The shock waves form when we force the flow to decelerate too quickly. We need to gradually compress the air back to subsonic speeds before it hits the combustion chamber. Those discontinuous pressure jumps across the shock fronts waste enormous amounts of energy. The flow literally goes from supersonic to subsonic almost instantaneously. Which explains why the prototype has been so inefficient. We're creating unnecessary shock losses instead of managing the transition smoothly. The area ratio between exit and throat determines the final Mach number. If we redesign those proportions, we can control exactly how much the flow accelerates.
sci-datasets/scilogues
ADA File Names vs. Package Names I inherited an ADA program where the source file names and package file names don't follow the default naming convention. ADA is new to me, so I may be missing something simple, but I can't see it in the GNAT Pro User's Guide. (This similar question didn't help me.) Here are a couple of examples: File Name: C_Comm_Config_S.Ada Package Name: Comm_Configuration File Name: D_Bus_Buffers_S.Ada Package Name: Bus_Buffers I think I have the _S.Ada and _B.Ada sorted out, but I can't find anything in the program source or build files that show the binding between the Package Name and the rest of the File Name. When I compile a file that doesn't use any other packages, I get a warning: file name does not match unit name... This appears to be from the prefix of C_ or D_, in this particular case. Also, I'm not clear if the prefixes C_ and D_ have any special meaning in the context of ADA, but if it does, I'd like to know about it. So I appear to have two issues, the Prefix of C_ or D_ and in some cases the rest of the file name doesn't match the package. You could use gnatname: see the User’s Guide. I copied subdirectories a/ and d/ from the ACATS test suite to a working directory and created a project file p.gpr: project p is for source_dirs use ("a", "d"); end p; and ran gnatname with gnatname -P p -d a -d d \*.ada which resulted in an edited p.gpr and two new files, p_naming.gpr and p_source_list.txt. These are rather long, but look like p.gpr: with "p_naming.gpr"; project P is for Source_List_File use "p_source_list.txt"; for Source_Dirs use ("a", "d"); package Naming renames P_Naming.Naming; end P; p_naming.gpr: project P_Naming is for Source_Files use (); package Naming is for Body ("d4a004b") use "d4a004b.ada"; for Body ("d4a004a") use "d4a004a.ada"; for Body ("d4a002b") use "d4a002b.ada"; ... for Body ("aa2010a_parent.boolean") use "aa2010a.ada" at 4; for Body ("aa2010a_parent") use "aa2010a.ada" at 3; for Spec ("aa2010a_parent") use "aa2010a.ada" at 2; for Spec ("aa2010a_typedef") use "aa2010a.ada" at 1; ... for Body ("a22006d") use "a22006d.ada"; for Body ("a22006c") use "a22006c.ada"; for Body ("a22006b") use "a22006b.ada”; end Naming; end P_Naming; The for Body ("aa2010a_parent") use "aa2010a.ada" at 3; is used when there’s more than one unit in the source file. p_source_list.txt: a22006b.ada a22006c.ada a22006d.ada a27003a.ada a29003a.ada ... d4a002b.ada d4a004a.ada d4a004b.ada When building, for example, test d4a004b, you have to use the file name and suffix: gnatmake -P p d4a004b.ada This seemed to work after I removed the backslash: "gnatname -P p -d src -v -v *.Ada" Thanks. I think that depends on how your shell (in my case, bash 3.2.53 on Mac OS X Mavericks) interprets wildcards. gnatname expects a pattern, so the “*” mustn’t be expanded even if there are matching files in the current directory. Enclosing in single or double quotes should work as well. The Ada standard does not say anything about source file naming conventions. As it appears that you use GNAT, I assume that you mean the "GNAT default naming convention". You can tell GNAT about alternatively named files in a Naming package inside your project files. A simple example: project OpenID is ... package Naming is for Implementation ("Util.Log.Loggers.Traceback") use "util-log-loggers-traceback-gnat.adb"; for Implementation ("Util.Serialize.IO.XML.Get_Location") use "util-serialize-io-xml-get_location-xmlada-4.adb"; end Naming; end OpenID;
common-pile/stackexchange_filtered
Events fired when the display power is switched On/Off I search for an event or if doesn't exist, a method to know if the screen off (Power Options – Control Panel - Turn off the display setting). None of these solutions work for me. So either I was wrong somewhere, or it's just not suitable. How to get the events when the screen/display goes to power OFF or ON? I expect some track or solution. The problem is that I don't know what I'm doing, if you could help me a little more it would be cool. I made this, but it doesn't work: internal static class NativeMethods { public static Guid GUID_MONITOR_POWER_ON = new Guid(0x02731015, 0x4510, 0x4526, 0x99, 0xE6, 0xE5, 0xA1, 0x7E, 0xBD, 0x1A, 0xEA); public const int DEVICE_NOTIFY_WINDOW_HANDLE = 0x00000000; public const int WM_POWERBROADCAST = 0x0218; public const int PBT_POWERSETTINGCHANGE = 0x8013; [StructLayout(LayoutKind.Sequential, Pack = 4)] public struct POWERBROADCAST_SETTING { public Guid PowerSetting; public uint DataLength; public byte Data; } [DllImport(@"User32", SetLastError = true, EntryPoint = "RegisterPowerSettingNotification", CallingConvention = CallingConvention.StdCall)] public static extern IntPtr RegisterPowerSettingNotification(IntPtr hRecipient, ref Guid PowerSettingGuid, Int32 Flags); [DllImport(@"User32", SetLastError = true, EntryPoint = "UnregisterPowerSettingNotification", CallingConvention = CallingConvention.StdCall)] public static extern bool UnregisterPowerSettingNotification(IntPtr handle); } private void WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { Debug.WriteLine("EVENT", "DEBUG"); } public form1() { NativeMethods.RegisterPowerSettingNotification(this.Handle, ref NativeMethods.GUID_MONITOR_POWER_ON, NativeMethods.DEVICE_NOTIFY_WINDOW_HANDLE); } The declarations are mostly correct, you just need to handle the messages when you're notified. Override OnHandleCreated, to be sure that the Window handle is valid when you pass it to the function. Override WndProc, to receive and process the WM_POWERBROADCAST event. Note that the Guid used in Windows 8+ is different from the one used in Window 7. Not much, in Windows 8+ is also available a POWERBROADCAST_SETTING.Data value of 0x02, including the Monitor Dimmed status; anyway, it's recommended that you use this Guid instead. You can check the OSVersion before calling RegisterPowerSettingNotification. This function returns a handle (IntPtr), which is used to call UnregisterPowerSettingNotification after. The first notification is sent as soon as your application begins to process the messages (you should receive a message informing you that the Monitor is On :). Note that these events are notified when the System turns On/Off or dims the Display power, not if you switch the Monitor's Power button On/Off. public partial class Form1 : Form { private IntPtr unRegPowerNotify = IntPtr.Zero; protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); var settingGuid = new NativeMethods.PowerSettingGuid(); Guid powerGuid = IsWindows8Plus() ? settingGuid.ConsoleDisplayState : settingGuid.MonitorPowerGuid; unRegPowerNotify = NativeMethods.RegisterPowerSettingNotification( this.Handle, powerGuid, NativeMethods.DEVICE_NOTIFY_WINDOW_HANDLE); } private bool IsWindows8Plus() { var version = Environment.OSVersion.Version; if (version.Major > 6) return true; // Windows 10+ if (version.Major == 6 && version.Minor > 1) return true; // Windows 8+ return false; // Windows 7 or less } protected override void WndProc(ref Message m) { switch (m.Msg) { case NativeMethods.WM_POWERBROADCAST: if (m.WParam == (IntPtr)NativeMethods.PBT_POWERSETTINGCHANGE) { var settings = (NativeMethods.POWERBROADCAST_SETTING)m.GetLParam( typeof(NativeMethods.POWERBROADCAST_SETTING)); switch (settings.Data) { case 0: Console.WriteLine("Monitor Power Off"); break; case 1: Console.WriteLine("Monitor Power On"); break; case 2: Console.WriteLine("Monitor Dimmed"); break; } } m.Result = (IntPtr)1; break; } base.WndProc(ref m); } protected override void OnFormClosing(FormClosingEventArgs e) { NativeMethods.UnregisterPowerSettingNotification(unRegPowerNotify); base.OnFormClosing(e); } } NativeMethods declarations: using System.Runtime.InteropServices; public class NativeMethods { internal const uint DEVICE_NOTIFY_WINDOW_HANDLE = 0x0; internal const uint DEVICE_NOTIFY_SERVICE_HANDLE = 0x1; internal const int WM_POWERBROADCAST = 0x0218; internal const int PBT_POWERSETTINGCHANGE = 0x8013; [DllImport("User32.dll", SetLastError = true)] internal static extern IntPtr RegisterPowerSettingNotification(IntPtr hWnd, [In] Guid PowerSettingGuid, uint Flags); [DllImport("User32.dll", SetLastError = true)] internal static extern bool UnregisterPowerSettingNotification(IntPtr hWnd); [StructLayout(LayoutKind.Sequential, Pack = 4)] internal struct POWERBROADCAST_SETTING { public Guid PowerSetting; public uint DataLength; public byte Data; } // https://learn.microsoft.com/en-us/windows/win32/power/power-setting-guids public class PowerSettingGuid { // 0=Powered by AC, 1=Powered by Battery, 2=Powered by short-term source (UPC) public Guid AcdcPowerSource { get; } = new Guid("5d3e9a59-e9D5-4b00-a6bd-ff34ff516548"); // POWERBROADCAST_SETTING.Data = 1-100 public Guid BatteryPercentageRemaining { get; } = new Guid("a7ad8041-b45a-4cae-87a3-eecbb468a9e1"); // Windows 8+: 0=Monitor Off, 1=Monitor On, 2=Monitor Dimmed public Guid ConsoleDisplayState { get; } = new Guid("6fe69556-704a-47a0-8f24-c28d936fda47"); // Windows 8+, Session 0 enabled: 0=User providing Input, 2=User Idle public Guid GlobalUserPresence { get; } = new Guid("786E8A1D-B427-4344-9207-09E70BDCBEA9"); // 0=Monitor Off, 1=Monitor On. public Guid MonitorPowerGuid { get; } = new Guid("02731015-4510-4526-99e6-e5a17ebd1aea"); // 0=Battery Saver Off, 1=Battery Saver On. public Guid PowerSavingStatus { get; } = new Guid("E00958C0-C213-4ACE-AC77-FECCED2EEEA5"); // Windows 8+: 0=Off, 1=On, 2=Dimmed public Guid SessionDisplayStatus { get; } = new Guid("2B84C20E-AD23-4ddf-93DB-05FFBD7EFCA5"); // Windows 8+, no Session 0: 0=User providing Input, 2=User Idle public Guid SessionUserPresence { get; } = new Guid("3C0F4548-C03F-4c4d-B9F2-237EDE686376"); // 0=Exiting away mode 1=Entering away mode public Guid SystemAwaymode { get; } = new Guid("98a7f580-01f7-48aa-9c0f-44352c29e5C0"); /* Windows 8+ */ // POWERBROADCAST_SETTING.Data not used public Guid IdleBackgroundTask { get; } = new Guid(0x515C31D8, 0xF734, 0x163D, 0xA0, 0xFD, 0x11, 0xA0, 0x8C, 0x91, 0xE8, 0xF1); public Guid PowerSchemePersonality { get; } = new Guid(0x245D8541, 0x3943, 0x4422, 0xB0, 0x25, 0x13, 0xA7, 0x84, 0xF6, 0x79, 0xB7); // The Following 3 Guids are the POWERBROADCAST_SETTING.Data result of PowerSchemePersonality public Guid MinPowerSavings { get; } = new Guid("8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c"); public Guid MaxPowerSavings { get; } = new Guid("a1841308-3541-4fab-bc81-f71556f20b4a"); public Guid TypicalPowerSavings { get; } = new Guid("381b4222-f694-41f0-9685-ff5bb260df2e"); } } It works, thank you very much. I'm analyzing the code, but I think that it's complicated to just get the screen power event ^^ It's standard procedure when you need to filter Windows messages. Of course, the NativeMethods class (often a partial class), is included in a Project linking a reusable class file. The Form's Handlers are often wired/unwired by a Model/Manager class. The same goes for the m.Msg of WndProc, which is handled elsewhere (another specialized class). So your Form will remain unchanged, in practice. If you do this kind of stuff often, you already have all these manager classes in place when the Project is created, so there's not much to add, except some code for new message type. IIRC, there's another method to get the same notification, using WMI Events. Not sure if you'ld consider it less complicated, though. There's less code for sure, since no PInvoking is involved. Yes I see. I would look for WMI.
common-pile/stackexchange_filtered
How to get the orthographic scaling of the camera to be exact in conjunction with the grid in isometric view? Is there an exact orthographic scaling that accurately reaches the top of the grid angle? I use "1.4142" in ortographic scale. But I'm not sure it's accurate enough. I use a resolution of 1024x1024. There is always an approximation, but with that parameters you should get something pretty close. Can you show the discrepancy? In my test file seems aligned enough...https://i.sstatic.net/d8b60.png The discrepancy is not noticeable in resolutions of 2048x2048 (literal, the same pixels in terms of similar orthographic scaling), which is enough, I still wanted to share the data, and also ask if anyone had the exact calculation haha, thanks for commenting One way to approach this is to use the 1x1 plane centered at the origin as a guide (as you've already done visually here), and to programmatically fit the parameters of the orthographic camera to just-barely contain that plane. Assuming no shape keys or other complications to the vertex data are present, and that you have the reference 1x1 plane chosen as the Active Object currently, and that the only camera in the scene is called "Camera" and is the orthographic camera of interest, here's some Python code for doing this, using the location of the 1x1 plane's vertices in Camera Space as a way of determining how close the Orthographic Camera is to containing them: from bpy_extras.object_utils import world_to_camera_view vxMax = max([world_to_camera_view(bpy.context.scene, bpy.data.objects['Camera'], bpy.context.object.matrix_world @ v.co).x for v in bpy.context.object.data.vertices]) vxMin = min([world_to_camera_view(bpy.context.scene, bpy.data.objects['Camera'], bpy.context.object.matrix_world @ v.co).x for v in bpy.context.object.data.vertices]) vyMax = max([world_to_camera_view(bpy.context.scene, bpy.data.objects['Camera'], bpy.context.object.matrix_world @ v.co).y for v in bpy.context.object.data.vertices]) vyMin = min([world_to_camera_view(bpy.context.scene, bpy.data.objects['Camera'], bpy.context.object.matrix_world @ v.co).y for v in bpy.context.object.data.vertices]) xDiam = vxMax - vxMin yDiam = vyMax - vyMin diam = max(xDiam, yDiam) bpy.data.objects['Camera'].data.ortho_scale = bpy.data.objects['Camera'].data.ortho_scale * diam Notes: this simple code works nicely with a scene containing just the default camera (but switched to Orthographic) and with the Default Cube replaced by a Plane. It needs to be generalized a bit if the camera may be 'off-center' initially, in order to re-center the camera as well as adjust the orthographic scale this only 'exactly' fits to whichever of the two dimensions is most constraining, given the target object and the orthographic camera's resolution (changing the ratio of the x, y resolutions of the orthographic camera changes the shape of its "view box", which can change which dimension is the most constraining one). I think it's also not very hard to generalize this a bit further to set the ratio of x, y resolutions so that the resulting orthographic camera is an exact fit to the target object in both dimensions, though, if that's needed. this isn't really "exact", in the sense that I haven't explicitly worked out the mathematics of the basis transformations needed to compute the orthographic camera parameter settings needed to exactly fit to Blender's overlay grid. But, I think this is very close to that; the 1x1 plane centered at the World Origin seems to fit the overlay grid exactly, and working out the specifics of the basis transformations would I suspect ultimately end up with an implementation that looks basically like this code, since that is exactly the kind of mathematical transformation built-ins like world_to_camera_view are responsible for providing Incredible, you solved it! and the camera was already centered if you add a camera with this: bpy.ops.object.camera_add(location=(30.60861, -30.60861, 30.60861)) object = bpy.context.scene.objects.active object.rotation_euler = (0.955324, 0, 0.785398) object.data.type = 'ORTHO' object.data.ortho_scale = 14.123 object.name = "Camera" bpy.ops.view3d.object_as_camera() For those who use Blender 2.79b and the code does not work(The @NeverConvex code) , they have to change the "@" to "*". Thanks!
common-pile/stackexchange_filtered
Application running as a service is not able to create the same number of processes as when it runs from cmd I have a Windows application which creates up to 35 processes and it's working OK when it's running from cmd. But when it is executed as a service on the same machine it is able to create only 20 processes and all other are killed because of some kind of resource exhaustion problem. The problem is persistent on one Windows 2003 server but not reproducible on other servers. Can it be because the system has run out of desktop heap? http://support.microsoft.com/kb/184802 How can I check it? Yes, it's possible that's what happening. You can monitor the Desktop Heap with the (wait for it....) Desktop Heap Monitor! You can get it here, or it's the third hit on Google for "desktop heap". Other hits on that search phrase give a lot of detail on diagnosing and fixing the issue, so do some reading, load that tool, and you're off to the races! Give it a few shots and then post back here letting us know if that helps you. Is it an application you created? If so you could probably have it log information about available memory and resources to a file to help narrow down what is happening. Is anything showing up in the logs for Windows? What account is the service running under? If you try running the service as your user that you're testing under does the same thing happen? Different environment variables, or a different security context? What is the process doing? It could be something with an odd security setting. There may be a tool with sysinternals that can help you debug the issue, like using procmon. That may show where the file or registry setting is getting a denied or fail error, depending on what the process is doing. Even if procmon couldn't help there may be other tools in the suite that will. Google for sysinternals (free from Microsoft) and see what their stuff can tell you.
common-pile/stackexchange_filtered
Ajax Timer control in asp.net c# I have the code for the ajax timer as follows.. As the time becomes 0 the page will be redirected to another page. <h3><asp:Label ID="timer" runat="server" Text="You will be redirected to the Authentication Page in..."></asp:Label> <asp:Timer id="asptimer" runat="server"></asp:Timer> <asp:ScriptManager ID="ScriptManager" runat="server" ></asp:ScriptManager> <asp:Label ID="Label1" runat="server" Text="5"></asp:Label> The c# code is protected void Page_Load(object sender, EventArgs e) { asptimer.Enabled = true; asptimer.Interval = 1000; asptimer.Tick += new EventHandler<EventArgs>(asptimer_tick); } protected void asptimer_tick(object sender, EventArgs e) { int i = (Convert.ToInt16(Label1.Text)); i = i - 1; Label1.Text = i.ToString(); if (i < 0) { asptimer.Enabled = false; Response.Redirect("Login.aspx"); } } Now.. i want to hide the delay of page redirection using this timer. That is as the timer is executing , simultaneously the page must also redirect . Or the delay in redirection must be shown by this timer. How to achieve this? Not sure what you are trying to do here. But, I will implement this using a client side timer. See the code below: WebForm1.aspx function LoadTimer() { var timeInterval = '<%= timeinterval %>'; var remainingSeconds = (timeInterval / 1000); var timeInterval = setInterval(function () { document.getElementById('divRemainingTime').innerHTML = "You will be redirected to the webform2 in... " + --remainingSeconds; if (remainingSeconds <= 0) { window.location.href = "Webform2.aspx"; clearInterval(timeInterval); } }, 1000); } <body onload="LoadTimer();"> <form id="form1" runat="server"> <div id="divRemainingTime" runat="server"></div> </form> </body> WebForm1.aspx.cs public int timeinterval = 5000;
common-pile/stackexchange_filtered
ElasticSearch Search After API - Index State Is there any way to prevent the previous search results to be returned from the search after API? I want to prevent the same document returning twice...(this could happen if the document was updated between search after API calls) not sure what you mean by "between search after API calls" - are you worried about the document appear on two different search pages? The search_after functionality does not protect you from this, as each search is independent from the previous one and thus can change if you indexed or deleted documents in between. if you need a guaranteed stable point in time snapshot of your data, you should use a scroll search. However this needs some resources (like open file handles) and thus should only be used for system administrative tasks but not for regular user search (of which you have many, this should not be used for every search).
common-pile/stackexchange_filtered
Can a voltage higher than 5V be applied to the 28BYJ-48 (5V) stepper motor? I want to automate my roller blinds by using an ESP (NodeMCU) and I was thinking of using a stepper motor. I had a 28BYJ-48(5V) stepper motor laying around with the ULN2003 driver it came with. Unfornltunately the torque is not high enough to roll the blinds up. I tried applying 7.5V to the driver and now the torque is enough. The stepoer motor does not much hotter than when I'm applying 5V to it. My question is: how bad or unsafe is it to apply a voltage higher than 5V to the motor? are you certain that you actually applied 5 V? ... did you measure the voltage at the motor? What about the current? How much current does the motor draw on 5V and 7.5V? @jstola, I found out that instead of 5V I was applying 6V and instead of 7.5V I was applying 8.5V. This is not an application where you want to use a stepper. You want a DC gearmotor. That said, steppers are current mode devices not voltage ones and best driven from a chopping driver using several times the rated current voltage to overcome winding inductance. I think using a stepper motor is the way to go because it an then keep track of the location of the blinds.
common-pile/stackexchange_filtered
JavaScript Date with jQuery Countdown I'm trying to show a simple countdown from 2 hours like so: $(function () { var timeout = new Date(20000); $('#countdown').countdown({until: timeout, compact: true, format: 'HMS'}); }); However I just get 00:00:00, any ideas why? Have you read the docs? It says: `There are four ways of instantiating a date: var d = new Date(); var d = new Date(milliseconds); var d = new Date(dateString); var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);` @Michael Yes I have read the docs, but not everyone is a JavaScript expert and understands this as naturally as others! You get 00:00:00, because new Date(20000); is actually Thu Jan 01 1970 00:00:20 GMT+0000 (GMT) like 40 years ago. :D What you need to do is either: var timeout = new Date(Date.now() + 20000); or var timeout = 20000; By the way: two hours is not 20000, it is 1000 (ms) * 60 (s) * 60 (min) * 2 == 7200000
common-pile/stackexchange_filtered
Cascade not working in hibernate properly In the below given code, cascade="save-update", is used for the Course class(bag) associated with the Student class. Student class is--> private int id; private String firstName; private String lastName; private Address address; private List<Course> courses; Course class is--> private int id; private String name; private int unit; hbm file for Student is--> <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate.Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="pojos.Student" table="Student"> <id name="id" type="integer" column="ID"> <generator class="increment" /> </id> <property name="firstName"> <column name="FIRST_NAME" /> </property> <property name="lastName"> <column name="LAST_NAME" /> </property> <many-to-one name="address" class="pojos.Address" column="ADDRESS_ID" cascade="save-update" /> <bag name="courses" inverse="true" cascade="save-update"> <key column="STUDENT_ID" /> <one-to-many class="pojos.Course" /> </bag> </class> </hibernate-mapping> Transaction I'm performing is simply--> Student stud = new Student("Ketan", "Dikshit"); Address address = new Address("Dm-Road", "Uttar Pradesh", "201301"); Course course1 = new Course("Core Java", 101); Course course2 = new Course("Advanced Java", 201); List<Course> courses = new ArrayList<Course>(); courses.add(course1); courses.add(course2); stud.setAddress(address); stud.setCourses(courses); try { tr = session.beginTransaction(); System.out.println("\n Transaction has begun..!!"); session.save(stud); tr.commit(); System.out.println("\n Transaction is Commit..!!"); session.close(); System.out.println("\n Session is Closed..!!"); } catch (Exception e) { System.out.println("\n Transaction is in errror..!!"); tr.rollback(); System.out.println("\n Transaction is RollBack..!!"); session.close(); System.out.println("\n Session is Closed..!!"); } Now,As per the code, The Courses table should be holding a column named "STUDENT_ID" with the primary key of the associated Student present for each entry in the Course table.But the column "STUDENT_ID" is not showing any data( all null values inserted). The query sequence is--> Transaction has begun..!! Hibernate: select max(ID) from Student Hibernate: select max(ID) from Address Hibernate: select max(ID) from Course Hibernate: insert into Address (STREET, CITY, ZIPCODE, ID) values (?, ?, ?, ?) Hibernate: insert into Student (FIRST_NAME, LAST_NAME, ADDRESS_ID, ID) values (?, ?, ?, ?) Hibernate: insert into Course (NAME, UNIT, ID) values (?, ?, ?) Hibernate: insert into Course (NAME, UNIT, ID) values (?, ?, ?) Transaction is Commit..!! Why is the column in Course table showing NULL values, instead of holding the id's for the Student?? Remove inverse="true" from your bag mapping otherwise the owner of this relation will be Course and not Student. That worked just about fine, But still whenever I hear this term inverse="true" , most often I find myself wrong footed, the reason being I've never been able to understand it clearly enough as to why and how this attribute works, I just know that it always should go into the declaration of 'many' whenever there is a one-to-many relation. Do help me with that if possible, (some links or clear explaination might help).
common-pile/stackexchange_filtered
POSTed JSON to Google Apps Script, need to extract value and place in Google Sheets I am posting a JSON to Google Apps Script and want to display a specific value from that JSON in Google Sheets. I use the following code to get the data into my sheet from this post function doPost(e) { Logger.log("I was called") if (typeof e !== 'undefined') Logger.log(e.parameter); var ss = SpreadsheetApp.openById("ID here") var sheet = ss.getSheetByName("Sheet1") sheet.getRange(1, 1).setValue(JSON.stringify(e)) return ContentService.createTextOutput(JSON.stringify(e)) } My sheet now displays: { "parameter":{ }, "contextPath":"", "contentLength":20, "queryString":"", "parameters":{ }, "postData":{ "type":"application/json", "length":20, "contents":"{\"myValue\":13}", "name":"postData" } } I only want it to display the value for myValue - which is the number 13 in this example. I've tried a number of things suggested on these forums, I figured I was getting there with the solution from this post, and changed the code to: function doPost(e) { Logger.log("I was called") if (typeof e !== 'undefined') Logger.log(e.parameter); var jsonString = e.postData.getDataAsString(); //added line var jsonData = JSON.parse(jsonString); // added line var ss = SpreadsheetApp.openById("ID here") var sheet = ss.getSheetByName("Sheet1") sheet.getRange(1, 1).setValue(JSON.stringify(jsonData.myValue)) //changed "e" to jsonData.myValue return ContentService.createTextOutput(JSON.stringify(jsonData.myValue)) //changed "e" to jsonData.myValue } This didn't work. As a simple marketer, I wrestled with this for 2 nights now and feel I am pretty much stuck. So any help would be kindly appreciated. Cheers! You can do something like the following: function doPost(request) { var ss = SpreadsheetApp.openById("ID here") var sheet = ss.getSheetByName("Sheet1") // Now Parse the body of your post request in to a data object var data = JSON.parse (request.postData.contents) //Now put the data in the sheet sheet.getRange(1, 1).setValue(data['myValue']) // Note no need to stringify // now do your other stuff The body of the post request is available to you in request .postData.contents. Here's the Google documentation You parse the content string into a JSON object and then access the fields you need. Thanks for your help, appreciate it! When I try your code, I keep getting an error on line 6 - TypeError: Cannot read property "postData" from undefined - when trying to parse the postdata contents. I changed "request" to "e" on line 6 since I guess this is a mixup from the two example posts I linked to. But both give the error. Any idea what I'm missing here? Thanks! My code had a bug. I was cutting and pasting from another code. I have changed it - see if it works now. If it does not, if you post the last version of your code that causing the error, I should be able to help you get passed it. Good luck The changed code works like a charm and solved my problem. Thank you for taking the time to figure this one out for me!
common-pile/stackexchange_filtered
Scrollview paging with images?! xCode 4.2 I've been searching for long time how to add images into a scrollview and enable paging, so when i swipe left or right the next or previus images shows. i havent find anything that works yet, the only thing i found was this Code below: - (void)viewDidLoad { [super viewDidLoad]; NSArray *colors = [NSArray arrayWithObjects:[UIColor orangeColor], [UIColor greenColor], [UIColor blueColor],[UIColor redColor], nil]; for (int i = 0; i < colors.count; i++) { CGRect frame; frame.origin.x = self.scrollView.frame.size.width * i; frame.origin.y = 0; frame.size = self.scrollView.frame.size; UIView *subview = [[UIView alloc] initWithFrame:frame]; subview.backgroundColor = [colors objectAtIndex:i]; [self.scrollView addSubview:subview]; } self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * colors.count, self.scrollView.frame.size.height); } Ofc this does enable paging but with colors only, i tryed change where the UIColor with [UIImage imageName: @"photo1.jpg"] but it doesnt work at all... So after searching for a few days i need to ask how to do it, how to have some images inside a scroll view and have paging enabled Thanks in advance for any help I did find the answer my self after all. kinda proud to be honest because ive been looking for that soo long. anyway what i should have done is change first of all the UIColor at the array with UIImage. like this: NSArray *images = [NSArray arrayWithObjects:[UIImage imageNamed:@"photo1.jpg"],[UIImage imageNamed:@"photo2.jpg"],[UIImage<EMAIL_ADDRESS>nil]; for (int i = 0; i < images.count; i++) { CGRect frame; frame.origin.x = self.scrollView.frame.size.width * i; frame.origin.y = 0; frame.size = self.scrollView.frame.size; and change the UIView with an UIImageView and works like a charm!!!
common-pile/stackexchange_filtered