qid
int64
1
74.7M
question
stringlengths
25
64.6k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
0
115k
response_k
stringlengths
3
61.5k
6,149,673
Recently I started Unit testing my application. This project (in Xcode4) was created without a unit test bundle so I had to set it up. I have followed the steps from here: <http://cocoawithlove.com/2009/12/sample-mac-application-with-complete.html> And It was working well for simple classes but now I am trying to test a class that depends on another and that on another, etc. First I got a linker error so I added `*.m` files to the test case target but now I get a warning for every class I am trying to test: > > Class Foo is implemented in both MyApp > and MyAppTestCase. One of the two will > be used. Which one is undefined. > > > I wonder why is that? How can I solve this? Maybe I missed something when setting the unit test target? ### Edit - The Solution * Set "Bundle Loader" correctly to `$(BUILT_PRODUCTS_DIR)/AppName.app/AppName` * Set "Symbols Hidden by Default" to **NO** (in Build Settings of the target application). This is where the linker errors come from because it is YES by default!. I've been struggling with this for so long!. Source: [Linking error for unit testing with XCode 4?](https://stackoverflow.com/questions/6461074/linking-error-for-unit-testing-with-xcode-4)
2011/05/27
[ "https://Stackoverflow.com/questions/6149673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/149008/" ]
For me this happened because I deployed to the device and then to the simulator as I have NSZombies enabled. The solution was to switch to the simulator configuration & do a Product -> Clean then switch to the device configuration & do the same. Error went away. It's to do with build cache.
Come across the same issues, My situation is Class NSNotification is implemented in both /System/Library/Frameworks/Foundation.framework/Foundation, is there any dude come across the same issue, any direction or advise will be appriciated.
6,149,673
Recently I started Unit testing my application. This project (in Xcode4) was created without a unit test bundle so I had to set it up. I have followed the steps from here: <http://cocoawithlove.com/2009/12/sample-mac-application-with-complete.html> And It was working well for simple classes but now I am trying to test a class that depends on another and that on another, etc. First I got a linker error so I added `*.m` files to the test case target but now I get a warning for every class I am trying to test: > > Class Foo is implemented in both MyApp > and MyAppTestCase. One of the two will > be used. Which one is undefined. > > > I wonder why is that? How can I solve this? Maybe I missed something when setting the unit test target? ### Edit - The Solution * Set "Bundle Loader" correctly to `$(BUILT_PRODUCTS_DIR)/AppName.app/AppName` * Set "Symbols Hidden by Default" to **NO** (in Build Settings of the target application). This is where the linker errors come from because it is YES by default!. I've been struggling with this for so long!. Source: [Linking error for unit testing with XCode 4?](https://stackoverflow.com/questions/6461074/linking-error-for-unit-testing-with-xcode-4)
2011/05/27
[ "https://Stackoverflow.com/questions/6149673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/149008/" ]
If you are using Cocoapods, your podfile only needs the dependencies in the section for the main target, not the test targets. If you do add duplicate dependencies for the test targets, you'll get the OP's error message. ``` target 'MyProject' do pod 'Parse' end target 'MyProjectTests' do end target 'MyProjectUITests' do end ```
For me this happened because I deployed to the device and then to the simulator as I have NSZombies enabled. The solution was to switch to the simulator configuration & do a Product -> Clean then switch to the device configuration & do the same. Error went away. It's to do with build cache.
6,149,673
Recently I started Unit testing my application. This project (in Xcode4) was created without a unit test bundle so I had to set it up. I have followed the steps from here: <http://cocoawithlove.com/2009/12/sample-mac-application-with-complete.html> And It was working well for simple classes but now I am trying to test a class that depends on another and that on another, etc. First I got a linker error so I added `*.m` files to the test case target but now I get a warning for every class I am trying to test: > > Class Foo is implemented in both MyApp > and MyAppTestCase. One of the two will > be used. Which one is undefined. > > > I wonder why is that? How can I solve this? Maybe I missed something when setting the unit test target? ### Edit - The Solution * Set "Bundle Loader" correctly to `$(BUILT_PRODUCTS_DIR)/AppName.app/AppName` * Set "Symbols Hidden by Default" to **NO** (in Build Settings of the target application). This is where the linker errors come from because it is YES by default!. I've been struggling with this for so long!. Source: [Linking error for unit testing with XCode 4?](https://stackoverflow.com/questions/6461074/linking-error-for-unit-testing-with-xcode-4)
2011/05/27
[ "https://Stackoverflow.com/questions/6149673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/149008/" ]
If you are using Cocoapods, your podfile only needs the dependencies in the section for the main target, not the test targets. If you do add duplicate dependencies for the test targets, you'll get the OP's error message. ``` target 'MyProject' do pod 'Parse' end target 'MyProjectTests' do end target 'MyProjectUITests' do end ```
The reason is that you override `RUNPATH_SEARCH_PATHS` of your App Target`s build setting defined in other target. **Solution:** > > Go to your App Target and find `RUNPATH_SEARCH_PATHS` build setting and use there `$(inherited)` flag for both: **Debug** and **Release** > > >
29,663,034
Here's the relevant parts of my code I'm having trouble with. ``` Sub Find_Target() Dim DayNum As Long Dim TargetName As String Dim TargetDay As Range Dim found As Variant DayNum = Cells(1, 9) Set TargetDay = ActiveWorkbook.Sheets("3-2015").Range("A1:B440") TargetDay.Activate Set found = TargetDay.Find(DayNum, LookIn:=xlValues) If found Is Nothing Then MsgBox "Nothing found!" Else TargetDay.Select End If End Sub ``` Column A contains a mix of merged and unmerged cells. Cells(1, 9) contains a date in general format. Periodically in column A/B will be a merged cell containing that same number, but in custom number format "dddd". The find command works if I change the number format to general, but otherwise found is Nothing. I've tried playing with the FindFormat option, but didn't have any luck there.
2015/04/15
[ "https://Stackoverflow.com/questions/29663034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4794222/" ]
If it uninstalls normally without any errors, then the most likely issue is that the uninstall requires elevation and your code is not running elevated, and so it fails. It will not ask the user for elevation during a silent uninstall! SetInternalUI works fine for uninstalls. For example, the following C++ snippet does exactly what you want, making the uninstall totally silent: ``` INSTALLUILEVEL il = MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); UINT n = MsiConfigureProductEx(productid, INSTALLLEVEL_DEFAULT, INSTALLSTATE_ABSENT, L"REBOOT=R"); ``` and that ConfigureProduct call uses the same API.
Try this reference of different ways to uninstall an MSI file (option 6 describes DTF): * **[Uninstalling an MSI file from the command line without using msiexec](https://stackoverflow.com/questions/450027/uninstalling-an-msi-file-from-the-command-line-without-using-msiexec/1055933#1055933)**. Unfortunately I don't have **Visual Studio** available to test with at the moment - I'll still give it a go though I can't test anything. Needless to say this makes answering difficult: * It is possible that your silent uninstaller is crashing and this is why it fails in silent mode. * Typically this would involve a **custom action** that might not be conditioned properly and runs inappropriately (or not at all whilst running in silent mode). Try to enable logging during silent uninstall as shown here (adjust the path to the log file as appropriately). The special `!` flag will **flush the log file** - meaning it is written continuously instead of in batches so no logging is lost due to any potential crashes (this slows the (un)installation process considerably): ```cs using Microsoft.Deployment.WindowsInstaller; public static void Uninstall( string productCode) { Installer.SetInternalUI(InstallUIOptions.Silent); Installer.ConfigureProduct(productCode, 0, InstallState.Absent, "REBOOT=\"R\" /L*V! c:\uninstall.log"); } ``` To find relevant information in the log file, check out this [**log file checking tip from Rob Mensching**](http://robmensching.com/blog/posts/2010/8/2/the-first-thing-i-do-with-an-msi-log/) (creator of Wix).
29,663,034
Here's the relevant parts of my code I'm having trouble with. ``` Sub Find_Target() Dim DayNum As Long Dim TargetName As String Dim TargetDay As Range Dim found As Variant DayNum = Cells(1, 9) Set TargetDay = ActiveWorkbook.Sheets("3-2015").Range("A1:B440") TargetDay.Activate Set found = TargetDay.Find(DayNum, LookIn:=xlValues) If found Is Nothing Then MsgBox "Nothing found!" Else TargetDay.Select End If End Sub ``` Column A contains a mix of merged and unmerged cells. Cells(1, 9) contains a date in general format. Periodically in column A/B will be a merged cell containing that same number, but in custom number format "dddd". The find command works if I change the number format to general, but otherwise found is Nothing. I've tried playing with the FindFormat option, but didn't have any luck there.
2015/04/15
[ "https://Stackoverflow.com/questions/29663034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4794222/" ]
Try this reference of different ways to uninstall an MSI file (option 6 describes DTF): * **[Uninstalling an MSI file from the command line without using msiexec](https://stackoverflow.com/questions/450027/uninstalling-an-msi-file-from-the-command-line-without-using-msiexec/1055933#1055933)**. Unfortunately I don't have **Visual Studio** available to test with at the moment - I'll still give it a go though I can't test anything. Needless to say this makes answering difficult: * It is possible that your silent uninstaller is crashing and this is why it fails in silent mode. * Typically this would involve a **custom action** that might not be conditioned properly and runs inappropriately (or not at all whilst running in silent mode). Try to enable logging during silent uninstall as shown here (adjust the path to the log file as appropriately). The special `!` flag will **flush the log file** - meaning it is written continuously instead of in batches so no logging is lost due to any potential crashes (this slows the (un)installation process considerably): ```cs using Microsoft.Deployment.WindowsInstaller; public static void Uninstall( string productCode) { Installer.SetInternalUI(InstallUIOptions.Silent); Installer.ConfigureProduct(productCode, 0, InstallState.Absent, "REBOOT=\"R\" /L*V! c:\uninstall.log"); } ``` To find relevant information in the log file, check out this [**log file checking tip from Rob Mensching**](http://robmensching.com/blog/posts/2010/8/2/the-first-thing-i-do-with-an-msi-log/) (creator of Wix).
> > Just to provide a better answer by linking to a new one: > **[Uninstalling program](https://stackoverflow.com/questions/52254206/uninstalling-program/52280957#52280957)**. > > > ***UAC & GUI***: Essentially your silent uninstall fails because it runs without elevation. When run interactively you get the UAC prompt and can elevate the rights - provided your account is an admin account and allows you to do so. When run silently this elevation can't happen and the uninstall fails. The solution is to run your application executable elevated. ***Exception Handling***: You might also want to use proper exception handling to ensure that the error message that results from the lack of elevation is reported to the user. See the code in the link above for an example. Here is a quick inlined section: ``` try { Installer.SetInternalUI(InstallUIOptions.Silent); // Set MSI GUI level Installer.ConfigureProduct(productcode, 0, InstallState.Absent, "REBOOT=\"ReallySuppress\""); } catch (Exception e) { Console.WriteLine("Exception: " + e.Message); Console.ReadLine (); // Keep console window open } ```
29,663,034
Here's the relevant parts of my code I'm having trouble with. ``` Sub Find_Target() Dim DayNum As Long Dim TargetName As String Dim TargetDay As Range Dim found As Variant DayNum = Cells(1, 9) Set TargetDay = ActiveWorkbook.Sheets("3-2015").Range("A1:B440") TargetDay.Activate Set found = TargetDay.Find(DayNum, LookIn:=xlValues) If found Is Nothing Then MsgBox "Nothing found!" Else TargetDay.Select End If End Sub ``` Column A contains a mix of merged and unmerged cells. Cells(1, 9) contains a date in general format. Periodically in column A/B will be a merged cell containing that same number, but in custom number format "dddd". The find command works if I change the number format to general, but otherwise found is Nothing. I've tried playing with the FindFormat option, but didn't have any luck there.
2015/04/15
[ "https://Stackoverflow.com/questions/29663034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4794222/" ]
If it uninstalls normally without any errors, then the most likely issue is that the uninstall requires elevation and your code is not running elevated, and so it fails. It will not ask the user for elevation during a silent uninstall! SetInternalUI works fine for uninstalls. For example, the following C++ snippet does exactly what you want, making the uninstall totally silent: ``` INSTALLUILEVEL il = MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); UINT n = MsiConfigureProductEx(productid, INSTALLLEVEL_DEFAULT, INSTALLSTATE_ABSENT, L"REBOOT=R"); ``` and that ConfigureProduct call uses the same API.
> > Just to provide a better answer by linking to a new one: > **[Uninstalling program](https://stackoverflow.com/questions/52254206/uninstalling-program/52280957#52280957)**. > > > ***UAC & GUI***: Essentially your silent uninstall fails because it runs without elevation. When run interactively you get the UAC prompt and can elevate the rights - provided your account is an admin account and allows you to do so. When run silently this elevation can't happen and the uninstall fails. The solution is to run your application executable elevated. ***Exception Handling***: You might also want to use proper exception handling to ensure that the error message that results from the lack of elevation is reported to the user. See the code in the link above for an example. Here is a quick inlined section: ``` try { Installer.SetInternalUI(InstallUIOptions.Silent); // Set MSI GUI level Installer.ConfigureProduct(productcode, 0, InstallState.Absent, "REBOOT=\"ReallySuppress\""); } catch (Exception e) { Console.WriteLine("Exception: " + e.Message); Console.ReadLine (); // Keep console window open } ```
8,990,251
**Interview Question** Phrased as: *If you have a property name collision, how would you specify the exact property to bind to in a Binding path expression (in XAML)?* I never faced this (property name collision) problem in any binding so far. With some reading I realized that this is possible in case I am binding to a overridden property because then I have two instances of this property (virtual in base, and overriden in derived) as far as resolution using Reflection is concerned. Which is what used by XAML. * Could there be any other case where XAML might face a property name collision? * Is there some support in API to handle/control that? (Instead of of course avoiding a collision) Thanks for your interest.
2012/01/24
[ "https://Stackoverflow.com/questions/8990251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93613/" ]
Sounds like a complete nonsense to me. Unless they wanted to talk about bindings, using 'disjointed' sources like `PriorityBinding` and `MultiBinding`. Frankly speaking I don't think overwritten properties can be involved into the matter as this is so much out of scope, you could equaly point out explicit interface implementations and many other things, which are clearly outside of WPF domain.
The best way I can think would be to use a ValueConverter. I don't think this really answers the question though since they're asking in a binding path expression, which I haven't seen to be possible. I'm not particularly fond of doing it this way because it feels like a hack, but it works at least for one way binding. Here's an example of how you might do it: XAML: ``` <StackPanel Name="stack"> <StackPanel.Resources> <loc:OverriddenMyPropertyConverter x:Key="BaseMyProperty"/> </StackPanel.Resources> <TextBox Text="{Binding Path=MyProperty}"/> <TextBox Text="{Binding Mode=OneWay, Converter={StaticResource BaseMyProperty}}"/> </StackPanel> ``` The DataContext of the StackPanel is an instance of MyClass. The first TextBox is bound to the MyClass.MyProperty property, and the second TextBox will be bound to the MyBaseClass.MyProperty property. Two way binding would be a bit more complex since the object actually being bound to the second TextBox is the MyClass object and not the MyProperty object. Code: ``` class MyClass : MyBaseClass { string myProperty = "overridden"; public new string MyProperty { get { return myProperty; } set { myProperty = value; } } } class MyBaseClass { string baseProperty = "base"; public string MyProperty { get { return baseProperty; } set { baseProperty = value; } } } class OverriddenMyPropertyConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return (value as MyBaseClass).MyProperty; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } ```
73,437,630
I'm building a small frontend application with react where I want to display data that I fetch from an API and put it in the state. But when I try to acces that data for displaying it (or log it to the console) I get undefined. It seems like I try to use the data before the call is done, but I dont get how I can change that. This is my code for the Component that makes my API call ``` import Search from '../Components/Search'; import '../App.css'; export default function People () { const [data, setData] = useState([]); const [isLoading, setIsLoading] = useState(true); useEffect(() => { fetch('https://swapi.dev/api/people') .then(res => res.json()) .then(data => { setData(data); setIsLoading(false); }) .catch(error => console.log(error)); }, []) console.log(data["results"]); return ( <React.Fragment> <div className="container-column"> <div className="item"> <Search /> </div> {isLoading && <p>Wait I'm Loading data for you</p>} render the data here {data["count"]}; </div> </React.Fragment> ) } ``` The data I get from the API looks like this: ``` "count": 82, "next": "https://swapi.dev/api/people/?page=2", "previous": null, "results": [ { "name": "Luke Skywalker", "height": "172", "mass": "77", "hair_color": "blond", "skin_color": "fair", "eye_color": "blue", "birth_year": "19BBY", "gender": "male", "homeworld": "https://swapi.dev/api/planets/1/", "films": [ "https://swapi.dev/api/films/1/", "https://swapi.dev/api/films/2/", "https://swapi.dev/api/films/3/", "https://swapi.dev/api/films/6/" ], "species": [], "vehicles": [ "https://swapi.dev/api/vehicles/14/", "https://swapi.dev/api/vehicles/30/" ], "starships": [ "https://swapi.dev/api/starships/12/", "https://swapi.dev/api/starships/22/" ], "created": "2014-12-09T13:50:51.644000Z", "edited": "2014-12-20T21:17:56.891000Z", "url": "https://swapi.dev/api/people/1/" }, { "name": "C-3PO", "height": "167", "mass": "75", "hair_color": "n/a", "skin_color": "gold", "eye_color": "yellow", "birth_year": "112BBY", "gender": "n/a", "homeworld": "https://swapi.dev/api/planets/1/", "films": [ "https://swapi.dev/api/films/1/", "https://swapi.dev/api/films/2/", "https://swapi.dev/api/films/3/", "https://swapi.dev/api/films/4/", "https://swapi.dev/api/films/5/", "https://swapi.dev/api/films/6/" ], "species": [ "https://swapi.dev/api/species/2/" ], "vehicles": [], "starships": [], "created": "2014-12-10T15:10:51.357000Z", "edited": "2014-12-20T21:17:50.309000Z", "url": "https://swapi.dev/api/people/2/" }, { "name": "R2-D2", "height": "96", "mass": "32", "hair_color": "n/a", "skin_color": "white, blue", "eye_color": "red", "birth_year": "33BBY", "gender": "n/a", "homeworld": "https://swapi.dev/api/planets/8/", "films": [ "https://swapi.dev/api/films/1/", "https://swapi.dev/api/films/2/", "https://swapi.dev/api/films/3/", "https://swapi.dev/api/films/4/", "https://swapi.dev/api/films/5/", "https://swapi.dev/api/films/6/" ], "species": [ "https://swapi.dev/api/species/2/" ], "vehicles": [], "starships": [], "created": "2014-12-10T15:11:50.376000Z", "edited": "2014-12-20T21:17:50.311000Z", "url": "https://swapi.dev/api/people/3/" }, { "name": "Darth Vader", "height": "202", "mass": "136", "hair_color": "none", "skin_color": "white", "eye_color": "yellow", "birth_year": "41.9BBY", "gender": "male", "homeworld": "https://swapi.dev/api/planets/1/", "films": [ "https://swapi.dev/api/films/1/", "https://swapi.dev/api/films/2/", "https://swapi.dev/api/films/3/", "https://swapi.dev/api/films/6/" ], "species": [], "vehicles": [], "starships": [ "https://swapi.dev/api/starships/13/" ], "created": "2014-12-10T15:18:20.704000Z", "edited": "2014-12-20T21:17:50.313000Z", "url": "https://swapi.dev/api/people/4/" }, { "name": "Leia Organa", "height": "150", "mass": "49", "hair_color": "brown", "skin_color": "light", "eye_color": "brown", "birth_year": "19BBY", "gender": "female", "homeworld": "https://swapi.dev/api/planets/2/", "films": [ "https://swapi.dev/api/films/1/", "https://swapi.dev/api/films/2/", "https://swapi.dev/api/films/3/", "https://swapi.dev/api/films/6/" ], "species": [], "vehicles": [ "https://swapi.dev/api/vehicles/30/" ], "starships": [], "created": "2014-12-10T15:20:09.791000Z", "edited": "2014-12-20T21:17:50.315000Z", "url": "https://swapi.dev/api/people/5/" }, { "name": "Owen Lars", "height": "178", "mass": "120", "hair_color": "brown, grey", "skin_color": "light", "eye_color": "blue", "birth_year": "52BBY", "gender": "male", "homeworld": "https://swapi.dev/api/planets/1/", "films": [ "https://swapi.dev/api/films/1/", "https://swapi.dev/api/films/5/", "https://swapi.dev/api/films/6/" ], "species": [], "vehicles": [], "starships": [], "created": "2014-12-10T15:52:14.024000Z", "edited": "2014-12-20T21:17:50.317000Z", "url": "https://swapi.dev/api/people/6/" }, { "name": "Beru Whitesun lars", "height": "165", "mass": "75", "hair_color": "brown", "skin_color": "light", "eye_color": "blue", "birth_year": "47BBY", "gender": "female", "homeworld": "https://swapi.dev/api/planets/1/", "films": [ "https://swapi.dev/api/films/1/", "https://swapi.dev/api/films/5/", "https://swapi.dev/api/films/6/" ], "species": [], "vehicles": [], "starships": [], "created": "2014-12-10T15:53:41.121000Z", "edited": "2014-12-20T21:17:50.319000Z", "url": "https://swapi.dev/api/people/7/" }, { "name": "R5-D4", "height": "97", "mass": "32", "hair_color": "n/a", "skin_color": "white, red", "eye_color": "red", "birth_year": "unknown", "gender": "n/a", "homeworld": "https://swapi.dev/api/planets/1/", "films": [ "https://swapi.dev/api/films/1/" ], "species": [ "https://swapi.dev/api/species/2/" ], "vehicles": [], "starships": [], "created": "2014-12-10T15:57:50.959000Z", "edited": "2014-12-20T21:17:50.321000Z", "url": "https://swapi.dev/api/people/8/" }, { "name": "Biggs Darklighter", "height": "183", "mass": "84", "hair_color": "black", "skin_color": "light", "eye_color": "brown", "birth_year": "24BBY", "gender": "male", "homeworld": "https://swapi.dev/api/planets/1/", "films": [ "https://swapi.dev/api/films/1/" ], "species": [], "vehicles": [], "starships": [ "https://swapi.dev/api/starships/12/" ], "created": "2014-12-10T15:59:50.509000Z", "edited": "2014-12-20T21:17:50.323000Z", "url": "https://swapi.dev/api/people/9/" }, { "name": "Obi-Wan Kenobi", "height": "182", "mass": "77", "hair_color": "auburn, white", "skin_color": "fair", "eye_color": "blue-gray", "birth_year": "57BBY", "gender": "male", "homeworld": "https://swapi.dev/api/planets/20/", "films": [ "https://swapi.dev/api/films/1/", "https://swapi.dev/api/films/2/", "https://swapi.dev/api/films/3/", "https://swapi.dev/api/films/4/", "https://swapi.dev/api/films/5/", "https://swapi.dev/api/films/6/" ], "species": [], "vehicles": [ "https://swapi.dev/api/vehicles/38/" ], "starships": [ "https://swapi.dev/api/starships/48/", "https://swapi.dev/api/starships/59/", "https://swapi.dev/api/starships/64/", "https://swapi.dev/api/starships/65/", "https://swapi.dev/api/starships/74/" ], "created": "2014-12-10T16:16:29.192000Z", "edited": "2014-12-20T21:17:50.325000Z", "url": "https://swapi.dev/api/people/10/" } ] } ``` On my console.log I first get two lines 'undefined' and then get the data I want (the results array). In my component the {data["count"]} renders after a while, but if I try to get deeper in the data structure (e.g. get the name value of the first item of the results array) I get 'Cannot read properties of undefined'.
2022/08/21
[ "https://Stackoverflow.com/questions/73437630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19815486/" ]
b. It doesn't matter if you write `item1`, `item4`, `5` or `10/2`; they all evaluate to the number five.
Short answer: B. Long answer: What List.Contains does is that it checks whether or not a list contains a value, e.g an int, bool or any other object. If you are wondering about the Equals method, well, the Equals method checks if two objects are the same value-wise. This means that the code for Contains is most likely just ```cs public void bool Contains(T value){ for(int i = 0; i < Count; i++){ if(self[i].Equals(value)) // Could prob be something else, and might use "==" instead of equals return true; } return false; } ```
27,399,772
I am new to web development, so this problem may be very simple. I have xampp installed and running, and am using netbeans latest version. I'm currently trying to follow a tutorial which requires me to make a couple controllers, yet the only page I can successfully load is index.php. I have made a new controller in application/controllers folder: ``` <?php class Blog extends CI_Controller { public function index() { echo 'Say something'; } } ?> ``` And tried to access it via ``` http://localhost/Something/Blog ``` But I get an error: ``` Object not found! The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again. If you think this is a server error, please contact the webmaster. Error 404 localhost Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.6.3 ``` p.s. ``` http://localhost/Something is loading fine. ``` And I've edited the .htaccess file: ``` RewriteEngine on RewriteCond %(REQUEST_FILENAME) !-f RewriteCond %(REQUEST_FILENAME) !-d RewriteRule ." index.php/$0 [PT,L] ``` I have been googling for the solution for 3 hours, I would appreciate any help :)
2014/12/10
[ "https://Stackoverflow.com/questions/27399772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4345320/" ]
Change .htaccess file to: ``` RewriteEngine on RewriteCond $1 !^(index\.php|resources|robots\.txt) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L,QSA] ``` Also, try accessing with: ``` http://localhost/Something/index.php/Blog ```
**Try this :** localhost/Something/index.php/controllername
27,399,772
I am new to web development, so this problem may be very simple. I have xampp installed and running, and am using netbeans latest version. I'm currently trying to follow a tutorial which requires me to make a couple controllers, yet the only page I can successfully load is index.php. I have made a new controller in application/controllers folder: ``` <?php class Blog extends CI_Controller { public function index() { echo 'Say something'; } } ?> ``` And tried to access it via ``` http://localhost/Something/Blog ``` But I get an error: ``` Object not found! The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again. If you think this is a server error, please contact the webmaster. Error 404 localhost Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.6.3 ``` p.s. ``` http://localhost/Something is loading fine. ``` And I've edited the .htaccess file: ``` RewriteEngine on RewriteCond %(REQUEST_FILENAME) !-f RewriteCond %(REQUEST_FILENAME) !-d RewriteRule ." index.php/$0 [PT,L] ``` I have been googling for the solution for 3 hours, I would appreciate any help :)
2014/12/10
[ "https://Stackoverflow.com/questions/27399772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4345320/" ]
Change .htaccess file to: ``` RewriteEngine on RewriteCond $1 !^(index\.php|resources|robots\.txt) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L,QSA] ``` Also, try accessing with: ``` http://localhost/Something/index.php/Blog ```
Also write name of `controller class` and `method` in small in browser url. you can access using: ``` http://localhost/index.php/something/blog ```
27,399,772
I am new to web development, so this problem may be very simple. I have xampp installed and running, and am using netbeans latest version. I'm currently trying to follow a tutorial which requires me to make a couple controllers, yet the only page I can successfully load is index.php. I have made a new controller in application/controllers folder: ``` <?php class Blog extends CI_Controller { public function index() { echo 'Say something'; } } ?> ``` And tried to access it via ``` http://localhost/Something/Blog ``` But I get an error: ``` Object not found! The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again. If you think this is a server error, please contact the webmaster. Error 404 localhost Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.6.3 ``` p.s. ``` http://localhost/Something is loading fine. ``` And I've edited the .htaccess file: ``` RewriteEngine on RewriteCond %(REQUEST_FILENAME) !-f RewriteCond %(REQUEST_FILENAME) !-d RewriteRule ." index.php/$0 [PT,L] ``` I have been googling for the solution for 3 hours, I would appreciate any help :)
2014/12/10
[ "https://Stackoverflow.com/questions/27399772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4345320/" ]
Change .htaccess file to: ``` RewriteEngine on RewriteCond $1 !^(index\.php|resources|robots\.txt) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L,QSA] ``` Also, try accessing with: ``` http://localhost/Something/index.php/Blog ```
Add htaccess this code my help ``` RewriteEngine on RewriteCond %{REQUEST_URI} ^system.* RewriteRule ^(.*)$ /index.php/$1 [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L] ```
10,771,129
I'm using devise gem to implement authentication in my Ruby On Rails application. Sometimes error messages are displayed such as: > > Prohibited an error being wellness saved from this user: Password is > too short (minimum is 6 characters) > > > What is the best way to translate these messages to another language?
2012/05/27
[ "https://Stackoverflow.com/questions/10771129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/673167/" ]
Go to `config/locales` and copy `devise.en.yml`, giving the file a name like devise.other\_language\_initials.yml. Then add your own translations. For more info on how to translate your application, go [here](http://guides.rubyonrails.org/i18n.html).
The fastest way is downloading a translation file to the language you want. You can find more about [**in this link**](https://github.com/plataformatec/devise/wiki/I18n). What you are going to find there is a bunch of files in different languages for Devise flash notifications that you can download and add to you application under **config/locales**. Hope that helps you! :)
12,778
I have been looking into this lately, just as a fun project. I know people say it can be done, and others say it makes no sense. Google search turns up mixed results. Since Minecraft Single Player is basically a local server you are on by yourself, and Minecraft Pi works great, shouldn't a multi-player server work with 2-5 people? I have looked at this site: <http://picraftbukkit.webs.com/pi-minecraft-server-how-to> and he says he has it working just fine. I've also looked at this thread: <http://www.minecraftforum.net/topic/1838765-will-a-raspberry-pi-work-well-as-a-minecraft-server/> and the response seems to be mixed. I know I would have to generate the world off the Pi, it would take *way* too long on the Pi, but beyond that, is this plausible? I would probably run a couple mods: Optifine, that one that lets you make teleporters, possibly Mo'Creatures, definitely Too Much TNT (with the bigger ones turned off), if I can Skyblock, Computer craft would be epic (but not essential), Treecapitor FOR SURE, but only one adding one at a time to see if the Pi can handle Mods. Optifine, and clearlag would be musts, just to keep the server usable, and I probably would include World Edit. Also, would I set the graphics split to higher GPU RAM or higher CPU RAM? I wouldn't use the Pi whilst the server was online, obviously, so it would be higher CPU, lower GPU, correct? From the elinux.org page for the RPi Advanced setup it says: > > So the RPF changed the firmware so that a single start.elf you now can > give the GPU exactly the amount you want, in chunks of 16MB, with 16MB > as minimum, and 128MB as maximum. > > > The new syntax is to use: > > > **gpu\_mem=(number of megabytes for the GPU)** > > > So for example putting > > > gpu\_mem=64 > > > will give the GPU 64 MB and whatever the rest is (either 192 or 448 > MB) to the ARM CPU. > > > This question: [Bramble Pi as Minecraft Server](https://raspberrypi.stackexchange.com/questions/7958/bramble-pi-as-minecraft-server?rq=1) seemed to show a way that I could run a server (albeit with a cluster, I would be using a single one). It said I would need Hardfloat Java (is that the default one that comes with the newest Raspbian?) One last thing, would I want to run this on a default Raspbian installation, or download/install everything I need on Arch (as Arch is lighter and would thus run faster). Can the Pi run Bukkit okay, or would a vanilla server work better?
2014/01/06
[ "https://raspberrypi.stackexchange.com/questions/12778", "https://raspberrypi.stackexchange.com", "https://raspberrypi.stackexchange.com/users/9475/" ]
Have you tried googling 'Minecraft Bukkit Server system requirements', google is your friend you know. (No offence, but The first result, second response [here](https://forums.bukkit.org/threads/system-requirements-for-home-server.6691/) gives a rough idea: > > Your biggest issue running a minecraft server seems to be the RAM. If > everyone is in the same chunk, you're fine. When everyone has their > own chunk and the 80 chunks around them, then things can get bad very > quickly. A rule of thumb is 100MB per player. The second biggest issue > is bandwidth. A good rule of thumb seems to be about .150Mbps upload > per player. CPU is... not really an issue at all, except during - as > you noted - map generation. I swear the server could run on an abacus > if you could figure out the I/O. > > > and as we know RPi has 512, using about 3-4 players should be fine (The remaning ~100MBs are for system and GPU) **EDIT** To answer the second part, which you noted that I missed in my answer. I googled a bit and found full instructions on [how to set up the Bukkit Server on RPi](http://picraftbukkit.webs.com/pi-minecraft-server-how-to) and it is running some plugins(listed in the howto I linked to), which means **YES, you can run plugins :)**
Not sure if this answers the whole question as I haven't tried setting the graphics split, but on my 512MB Pi running Raspbian I've tried running Minecraft servers. The first time I used Spigot (based on Bukkit I think) with no plugins (apart from PluginMetrics which I assume was installed by default) and the second time I used the vanilla server from minecraft.net. Generating the worlds took around 20-30 mins I think (can't remember exactly but something like that - obviously a lot longer than using a normal PC). With just 1 player (myself), it seemed to work when I moved around and placed/destroyed blocks in Creative but in Survival there was quite a lot of lag when placing/destroying blocks. However, both times the servers ran with the desktop running, and they may have run better in console mode without booting to the desktop. If you use Raspbian I would recommend trying the server without booting to the desktop so less resources are used for other processes. I've only used Raspbian (and RaspBMC) on the Pi and have never used Arch so I can't compare them but it sounds like a good idea as I've heard it's more lightweight.
12,778
I have been looking into this lately, just as a fun project. I know people say it can be done, and others say it makes no sense. Google search turns up mixed results. Since Minecraft Single Player is basically a local server you are on by yourself, and Minecraft Pi works great, shouldn't a multi-player server work with 2-5 people? I have looked at this site: <http://picraftbukkit.webs.com/pi-minecraft-server-how-to> and he says he has it working just fine. I've also looked at this thread: <http://www.minecraftforum.net/topic/1838765-will-a-raspberry-pi-work-well-as-a-minecraft-server/> and the response seems to be mixed. I know I would have to generate the world off the Pi, it would take *way* too long on the Pi, but beyond that, is this plausible? I would probably run a couple mods: Optifine, that one that lets you make teleporters, possibly Mo'Creatures, definitely Too Much TNT (with the bigger ones turned off), if I can Skyblock, Computer craft would be epic (but not essential), Treecapitor FOR SURE, but only one adding one at a time to see if the Pi can handle Mods. Optifine, and clearlag would be musts, just to keep the server usable, and I probably would include World Edit. Also, would I set the graphics split to higher GPU RAM or higher CPU RAM? I wouldn't use the Pi whilst the server was online, obviously, so it would be higher CPU, lower GPU, correct? From the elinux.org page for the RPi Advanced setup it says: > > So the RPF changed the firmware so that a single start.elf you now can > give the GPU exactly the amount you want, in chunks of 16MB, with 16MB > as minimum, and 128MB as maximum. > > > The new syntax is to use: > > > **gpu\_mem=(number of megabytes for the GPU)** > > > So for example putting > > > gpu\_mem=64 > > > will give the GPU 64 MB and whatever the rest is (either 192 or 448 > MB) to the ARM CPU. > > > This question: [Bramble Pi as Minecraft Server](https://raspberrypi.stackexchange.com/questions/7958/bramble-pi-as-minecraft-server?rq=1) seemed to show a way that I could run a server (albeit with a cluster, I would be using a single one). It said I would need Hardfloat Java (is that the default one that comes with the newest Raspbian?) One last thing, would I want to run this on a default Raspbian installation, or download/install everything I need on Arch (as Arch is lighter and would thus run faster). Can the Pi run Bukkit okay, or would a vanilla server work better?
2014/01/06
[ "https://raspberrypi.stackexchange.com/questions/12778", "https://raspberrypi.stackexchange.com", "https://raspberrypi.stackexchange.com/users/9475/" ]
Have you tried googling 'Minecraft Bukkit Server system requirements', google is your friend you know. (No offence, but The first result, second response [here](https://forums.bukkit.org/threads/system-requirements-for-home-server.6691/) gives a rough idea: > > Your biggest issue running a minecraft server seems to be the RAM. If > everyone is in the same chunk, you're fine. When everyone has their > own chunk and the 80 chunks around them, then things can get bad very > quickly. A rule of thumb is 100MB per player. The second biggest issue > is bandwidth. A good rule of thumb seems to be about .150Mbps upload > per player. CPU is... not really an issue at all, except during - as > you noted - map generation. I swear the server could run on an abacus > if you could figure out the I/O. > > > and as we know RPi has 512, using about 3-4 players should be fine (The remaning ~100MBs are for system and GPU) **EDIT** To answer the second part, which you noted that I missed in my answer. I googled a bit and found full instructions on [how to set up the Bukkit Server on RPi](http://picraftbukkit.webs.com/pi-minecraft-server-how-to) and it is running some plugins(listed in the howto I linked to), which means **YES, you can run plugins :)**
I have had a Bukkit server running at various times, however performance is laggy, and you shouldn't plan on doing much else on the pi, certainly not running a Desktop, etc. I have a step-by-step [here](http://stacey-campbell.com/rpi-bukkit.html). By and far the most important issues are: 1. Allocate as much RAM as possible to the CPU, so select the lowest graphics shared allocation you can manage, and avoid having other applications contending for RAM. 2. Enable the fastest dynamic overclocking your pi can manage. 3. Limit the number of chunks a player needs to read/modify by reducing visibility, limiting flying, shutting off TNT, etc. Generating a new world does take a while, but not more than about 15 minutes that I saw. Hardfloat java is now available as a standard package for Raspbian.
513,417
I have two questions related to the FlashMessenger view helper. Both questions are to do this code: My action method: ``` private $_messages; // set to $this->_helper->FlashMessenger; in init() public function loginAction() { // > login validation < // Switch based on the result code switch ($result->getCode()) { // > snip several cases < case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID: $this->_messages->addMessage("That wasn't the right password."); break; case Zend_Auth_Result::SUCCESS: $this->_messages->addMessage('Logged you in successfully. Welcome back!'); $this->_helper->Redirector('index', 'home'); break; } // >snip< $this->view->messages = $this->_messages->getMessages(); $this->render(); } ``` My layout (Zend\_Layout) view script: ``` <?php if (isset($this->messages) && count($this->messages) > 0) { print_r($this->messages); //$this->partialLoop('partials/messages.phtml', $this->messages); } ?> ``` ### Why is the message not output the first time it is set? I have a feeling this is to do with the messenger being stored in sessions but I'm sure it's to do with my implementation. When I submit a bad value to my form I don't get a message until I either send the form again or refresh. ### What is a good way of sending this to the `PartialLoop` helper? The output of the messenger is something like: ``` Array( [0] => 'Message', [1] => 'Second message' //etc. ) ``` But this is no good for a `PartialLoop` as I need to get the message (which needs each message to be an array, containing a `'message' => 'Message string'` key/value pair). Is there a better method instead of rewriting the array before submitting it to the view?
2009/02/04
[ "https://Stackoverflow.com/questions/513417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
This entry in the BCL Team Blog gives a nice overview: "[Regular Expression performance](http://blogs.msdn.com/bclteam/archive/2004/11/12/256783.aspx)". In short, there are three types of regex (each executing faster than the previous one): 1. **interpreted** fast to create on the fly, slow to execute 2. **compiled** (the one you seem to ask about) slower to create on the fly, fast to execute (good for execution in loops) 3. **pre-compiled** create at compile time of your app (no run-time creation penalty), fast to execute So, if you intend to execute the regex only once, or in a non-performance-critical section of your app (i.e. user input validation), you are fine with option 1. If you intend to run the regex in a loop (i.e. line-by-line parsing of file), you should go with option 2. If you have many regexes that will never change for your app and are used intensely, you could go with option 3.
1) [Base Class Library Team on compiled regex](http://blogs.msdn.com/bclteam/archive/2004/11/12/256783.aspx) 2) [Coding Horror, referencing #1 with some good points on the tradeoffs](https://blog.codinghorror.com/to-compile-or-not-to-compile/)
513,417
I have two questions related to the FlashMessenger view helper. Both questions are to do this code: My action method: ``` private $_messages; // set to $this->_helper->FlashMessenger; in init() public function loginAction() { // > login validation < // Switch based on the result code switch ($result->getCode()) { // > snip several cases < case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID: $this->_messages->addMessage("That wasn't the right password."); break; case Zend_Auth_Result::SUCCESS: $this->_messages->addMessage('Logged you in successfully. Welcome back!'); $this->_helper->Redirector('index', 'home'); break; } // >snip< $this->view->messages = $this->_messages->getMessages(); $this->render(); } ``` My layout (Zend\_Layout) view script: ``` <?php if (isset($this->messages) && count($this->messages) > 0) { print_r($this->messages); //$this->partialLoop('partials/messages.phtml', $this->messages); } ?> ``` ### Why is the message not output the first time it is set? I have a feeling this is to do with the messenger being stored in sessions but I'm sure it's to do with my implementation. When I submit a bad value to my form I don't get a message until I either send the form again or refresh. ### What is a good way of sending this to the `PartialLoop` helper? The output of the messenger is something like: ``` Array( [0] => 'Message', [1] => 'Second message' //etc. ) ``` But this is no good for a `PartialLoop` as I need to get the message (which needs each message to be an array, containing a `'message' => 'Message string'` key/value pair). Is there a better method instead of rewriting the array before submitting it to the view?
2009/02/04
[ "https://Stackoverflow.com/questions/513417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
This entry in the BCL Team Blog gives a nice overview: "[Regular Expression performance](http://blogs.msdn.com/bclteam/archive/2004/11/12/256783.aspx)". In short, there are three types of regex (each executing faster than the previous one): 1. **interpreted** fast to create on the fly, slow to execute 2. **compiled** (the one you seem to ask about) slower to create on the fly, fast to execute (good for execution in loops) 3. **pre-compiled** create at compile time of your app (no run-time creation penalty), fast to execute So, if you intend to execute the regex only once, or in a non-performance-critical section of your app (i.e. user input validation), you are fine with option 1. If you intend to run the regex in a loop (i.e. line-by-line parsing of file), you should go with option 2. If you have many regexes that will never change for your app and are used intensely, you could go with option 3.
It should be noted that the performance of regular expressions since .NET 2.0 has been improved with an MRU cache of uncompiled regular expressions. The Regex library code no longer reinterprets the same un-compiled regular expression every time. So there is potentially a bigger performance *penalty* with a compiled and on the fly regular expression. In addition to slower load times, the system also uses more memory to compile the regular expression to opcodes. Essentially, the current advice is either do not compile a regular expression, or compile them in advance to a separate assembly. Ref: BCL Team Blog [Regular Expression performance [David Gutierrez]](http://blogs.msdn.com/bclteam/archive/2004/11/12/256783.aspx)
513,417
I have two questions related to the FlashMessenger view helper. Both questions are to do this code: My action method: ``` private $_messages; // set to $this->_helper->FlashMessenger; in init() public function loginAction() { // > login validation < // Switch based on the result code switch ($result->getCode()) { // > snip several cases < case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID: $this->_messages->addMessage("That wasn't the right password."); break; case Zend_Auth_Result::SUCCESS: $this->_messages->addMessage('Logged you in successfully. Welcome back!'); $this->_helper->Redirector('index', 'home'); break; } // >snip< $this->view->messages = $this->_messages->getMessages(); $this->render(); } ``` My layout (Zend\_Layout) view script: ``` <?php if (isset($this->messages) && count($this->messages) > 0) { print_r($this->messages); //$this->partialLoop('partials/messages.phtml', $this->messages); } ?> ``` ### Why is the message not output the first time it is set? I have a feeling this is to do with the messenger being stored in sessions but I'm sure it's to do with my implementation. When I submit a bad value to my form I don't get a message until I either send the form again or refresh. ### What is a good way of sending this to the `PartialLoop` helper? The output of the messenger is something like: ``` Array( [0] => 'Message', [1] => 'Second message' //etc. ) ``` But this is no good for a `PartialLoop` as I need to get the message (which needs each message to be an array, containing a `'message' => 'Message string'` key/value pair). Is there a better method instead of rewriting the array before submitting it to the view?
2009/02/04
[ "https://Stackoverflow.com/questions/513417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
`RegexOptions.Compiled` instructs the regular expression engine to compile the regular expression expression into IL using lightweight code generation ([LCG](https://learn.microsoft.com/en-us/archive/blogs/joelpob/hello-world-lcg-lightweight-code-gen-style)). This compilation happens during the construction of the object and **heavily** slows it down. In turn, matches using the regular expression are faster. If you do not specify this flag, your regular expression is considered "interpreted". Take this example: ```cs public static void TimeAction(string description, int times, Action func) { // warmup func(); var watch = new Stopwatch(); watch.Start(); for (int i = 0; i < times; i++) { func(); } watch.Stop(); Console.Write(description); Console.WriteLine(" Time Elapsed {0} ms", watch.ElapsedMilliseconds); } static void Main(string[] args) { var simple = "^\\d+$"; var medium = @"^((to|from)\W)?(?<url>http://[\w\.:]+)/questions/(?<questionId>\d+)(/(\w|-)*)?(/(?<answerId>\d+))?"; var complex = @"^(([^<>()[\]\\.,;:\s@""]+" + @"(\.[^<>()[\]\\.,;:\s@""]+)*)|("".+""))@" + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+" + @"[a-zA-Z]{2,}))$"; string[] numbers = new string[] {"1","two", "8378373", "38737", "3873783z"}; string[] emails = new string[] { "sam@sam.com", "sss@s", "sjg@ddd.com.au.au", "onelongemail@oneverylongemail.com" }; foreach (var item in new[] { new {Pattern = simple, Matches = numbers, Name = "Simple number match"}, new {Pattern = medium, Matches = emails, Name = "Simple email match"}, new {Pattern = complex, Matches = emails, Name = "Complex email match"} }) { int i = 0; Regex regex; TimeAction(item.Name + " interpreted uncached single match (x1000)", 1000, () => { regex = new Regex(item.Pattern); regex.Match(item.Matches[i++ % item.Matches.Length]); }); i = 0; TimeAction(item.Name + " compiled uncached single match (x1000)", 1000, () => { regex = new Regex(item.Pattern, RegexOptions.Compiled); regex.Match(item.Matches[i++ % item.Matches.Length]); }); regex = new Regex(item.Pattern); i = 0; TimeAction(item.Name + " prepared interpreted match (x1000000)", 1000000, () => { regex.Match(item.Matches[i++ % item.Matches.Length]); }); regex = new Regex(item.Pattern, RegexOptions.Compiled); i = 0; TimeAction(item.Name + " prepared compiled match (x1000000)", 1000000, () => { regex.Match(item.Matches[i++ % item.Matches.Length]); }); } } ``` It performs 4 tests on 3 different regular expressions. First it tests a **single** once off match (compiled vs non compiled). Second it tests repeat matches that reuse the same regular expression. The results on my machine (compiled in release, no debugger attached) ### 1000 single matches (construct Regex, Match and dispose) ``` Type | Platform | Trivial Number | Simple Email Check | Ext Email Check ------------------------------------------------------------------------------ Interpreted | x86 | 4 ms | 26 ms | 31 ms Interpreted | x64 | 5 ms | 29 ms | 35 ms Compiled | x86 | 913 ms | 3775 ms | 4487 ms Compiled | x64 | 3300 ms | 21985 ms | 22793 ms ``` ### 1,000,000 matches - reusing the Regex object ``` Type | Platform | Trivial Number | Simple Email Check | Ext Email Check ------------------------------------------------------------------------------ Interpreted | x86 | 422 ms | 461 ms | 2122 ms Interpreted | x64 | 436 ms | 463 ms | 2167 ms Compiled | x86 | 279 ms | 166 ms | 1268 ms Compiled | x64 | 281 ms | 176 ms | 1180 ms ``` These results show that compiled regular expressions can be up to **60%** faster for cases where you reuse the `Regex` object. **However** in some cases can be over **3 orders of magnitude** slower to construct. It also shows that the **x64 version** of .NET can be **5 to 6 times slower** when it comes to compilation of regular expressions. --- The recommendation would be to **use the compiled version** in cases where either 1. You do not care about object initialization cost and need the extra performance boost. (note we are talking fractions of a millisecond here) 2. You care a little bit about initialization cost, but are reusing the Regex object so many times that it will compensate for it during your application life cycle. --- ### Spanner in the works, the Regex cache The regular expression engine contains an LRU cache which holds the last 15 regular expressions that were tested using the static methods on the `Regex` class. For example: `Regex.Replace`, `Regex.Match` etc.. all use the Regex cache. The size of the cache can be increased by setting [`Regex.CacheSize`](http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.cachesize.aspx). It accepts changes in size any time during your application's life cycle. New regular expressions are only cached **by the static helpers** on the Regex class. If you construct your objects the cache is checked (for reuse and bumped), however, the regular expression you construct is **not appended to the cache**. This cache is a **trivial** LRU cache, it is implemented using a simple double linked list. If you happen to increase it to 5000, and use 5000 different calls on the static helpers, every regular expression construction will crawl the 5000 entries to see if it has previously been cached. There is a **lock** around the check, so the check can decrease parallelism and introduce thread blocking. The number is set quite low to protect yourself from cases like this, though in some cases you may have no choice but to increase it. My **strong recommendation** would be **never** pass the `RegexOptions.Compiled` option to a static helper. For example: ```cs // WARNING: bad code Regex.IsMatch("10000", @"\\d+", RegexOptions.Compiled) ``` The reason being that you are heavily risking a miss on the LRU cache which will trigger a **super expensive** compile. Additionally, you have no idea what the libraries you depend on are doing, so have little ability to control or predict the **best possible** size of the cache. See also: [BCL team blog](https://blogs.msdn.microsoft.com/bclteam/2010/06/25/optimizing-regular-expression-performance-part-i-working-with-the-regex-class-and-regex-objects-ron-petrusha/) --- **Note** : this is relevant for .NET 2.0 and .NET 4.0. There are some expected changes in 4.5 that may cause this to be revised.
This entry in the BCL Team Blog gives a nice overview: "[Regular Expression performance](http://blogs.msdn.com/bclteam/archive/2004/11/12/256783.aspx)". In short, there are three types of regex (each executing faster than the previous one): 1. **interpreted** fast to create on the fly, slow to execute 2. **compiled** (the one you seem to ask about) slower to create on the fly, fast to execute (good for execution in loops) 3. **pre-compiled** create at compile time of your app (no run-time creation penalty), fast to execute So, if you intend to execute the regex only once, or in a non-performance-critical section of your app (i.e. user input validation), you are fine with option 1. If you intend to run the regex in a loop (i.e. line-by-line parsing of file), you should go with option 2. If you have many regexes that will never change for your app and are used intensely, you could go with option 3.
513,417
I have two questions related to the FlashMessenger view helper. Both questions are to do this code: My action method: ``` private $_messages; // set to $this->_helper->FlashMessenger; in init() public function loginAction() { // > login validation < // Switch based on the result code switch ($result->getCode()) { // > snip several cases < case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID: $this->_messages->addMessage("That wasn't the right password."); break; case Zend_Auth_Result::SUCCESS: $this->_messages->addMessage('Logged you in successfully. Welcome back!'); $this->_helper->Redirector('index', 'home'); break; } // >snip< $this->view->messages = $this->_messages->getMessages(); $this->render(); } ``` My layout (Zend\_Layout) view script: ``` <?php if (isset($this->messages) && count($this->messages) > 0) { print_r($this->messages); //$this->partialLoop('partials/messages.phtml', $this->messages); } ?> ``` ### Why is the message not output the first time it is set? I have a feeling this is to do with the messenger being stored in sessions but I'm sure it's to do with my implementation. When I submit a bad value to my form I don't get a message until I either send the form again or refresh. ### What is a good way of sending this to the `PartialLoop` helper? The output of the messenger is something like: ``` Array( [0] => 'Message', [1] => 'Second message' //etc. ) ``` But this is no good for a `PartialLoop` as I need to get the message (which needs each message to be an array, containing a `'message' => 'Message string'` key/value pair). Is there a better method instead of rewriting the array before submitting it to the view?
2009/02/04
[ "https://Stackoverflow.com/questions/513417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
This entry in the BCL Team Blog gives a nice overview: "[Regular Expression performance](http://blogs.msdn.com/bclteam/archive/2004/11/12/256783.aspx)". In short, there are three types of regex (each executing faster than the previous one): 1. **interpreted** fast to create on the fly, slow to execute 2. **compiled** (the one you seem to ask about) slower to create on the fly, fast to execute (good for execution in loops) 3. **pre-compiled** create at compile time of your app (no run-time creation penalty), fast to execute So, if you intend to execute the regex only once, or in a non-performance-critical section of your app (i.e. user input validation), you are fine with option 1. If you intend to run the regex in a loop (i.e. line-by-line parsing of file), you should go with option 2. If you have many regexes that will never change for your app and are used intensely, you could go with option 3.
This does not answer the question but I recommend doing this: ``` [RegexGenerator($@"MyPatter")] public partial Regex Regex_SomeRegex(); ``` That way you get best of both worlds. It will be fast at initialization because its created at compile time. And it will also be fast when using it.
513,417
I have two questions related to the FlashMessenger view helper. Both questions are to do this code: My action method: ``` private $_messages; // set to $this->_helper->FlashMessenger; in init() public function loginAction() { // > login validation < // Switch based on the result code switch ($result->getCode()) { // > snip several cases < case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID: $this->_messages->addMessage("That wasn't the right password."); break; case Zend_Auth_Result::SUCCESS: $this->_messages->addMessage('Logged you in successfully. Welcome back!'); $this->_helper->Redirector('index', 'home'); break; } // >snip< $this->view->messages = $this->_messages->getMessages(); $this->render(); } ``` My layout (Zend\_Layout) view script: ``` <?php if (isset($this->messages) && count($this->messages) > 0) { print_r($this->messages); //$this->partialLoop('partials/messages.phtml', $this->messages); } ?> ``` ### Why is the message not output the first time it is set? I have a feeling this is to do with the messenger being stored in sessions but I'm sure it's to do with my implementation. When I submit a bad value to my form I don't get a message until I either send the form again or refresh. ### What is a good way of sending this to the `PartialLoop` helper? The output of the messenger is something like: ``` Array( [0] => 'Message', [1] => 'Second message' //etc. ) ``` But this is no good for a `PartialLoop` as I need to get the message (which needs each message to be an array, containing a `'message' => 'Message string'` key/value pair). Is there a better method instead of rewriting the array before submitting it to the view?
2009/02/04
[ "https://Stackoverflow.com/questions/513417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
It should be noted that the performance of regular expressions since .NET 2.0 has been improved with an MRU cache of uncompiled regular expressions. The Regex library code no longer reinterprets the same un-compiled regular expression every time. So there is potentially a bigger performance *penalty* with a compiled and on the fly regular expression. In addition to slower load times, the system also uses more memory to compile the regular expression to opcodes. Essentially, the current advice is either do not compile a regular expression, or compile them in advance to a separate assembly. Ref: BCL Team Blog [Regular Expression performance [David Gutierrez]](http://blogs.msdn.com/bclteam/archive/2004/11/12/256783.aspx)
1) [Base Class Library Team on compiled regex](http://blogs.msdn.com/bclteam/archive/2004/11/12/256783.aspx) 2) [Coding Horror, referencing #1 with some good points on the tradeoffs](https://blog.codinghorror.com/to-compile-or-not-to-compile/)
513,417
I have two questions related to the FlashMessenger view helper. Both questions are to do this code: My action method: ``` private $_messages; // set to $this->_helper->FlashMessenger; in init() public function loginAction() { // > login validation < // Switch based on the result code switch ($result->getCode()) { // > snip several cases < case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID: $this->_messages->addMessage("That wasn't the right password."); break; case Zend_Auth_Result::SUCCESS: $this->_messages->addMessage('Logged you in successfully. Welcome back!'); $this->_helper->Redirector('index', 'home'); break; } // >snip< $this->view->messages = $this->_messages->getMessages(); $this->render(); } ``` My layout (Zend\_Layout) view script: ``` <?php if (isset($this->messages) && count($this->messages) > 0) { print_r($this->messages); //$this->partialLoop('partials/messages.phtml', $this->messages); } ?> ``` ### Why is the message not output the first time it is set? I have a feeling this is to do with the messenger being stored in sessions but I'm sure it's to do with my implementation. When I submit a bad value to my form I don't get a message until I either send the form again or refresh. ### What is a good way of sending this to the `PartialLoop` helper? The output of the messenger is something like: ``` Array( [0] => 'Message', [1] => 'Second message' //etc. ) ``` But this is no good for a `PartialLoop` as I need to get the message (which needs each message to be an array, containing a `'message' => 'Message string'` key/value pair). Is there a better method instead of rewriting the array before submitting it to the view?
2009/02/04
[ "https://Stackoverflow.com/questions/513417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
`RegexOptions.Compiled` instructs the regular expression engine to compile the regular expression expression into IL using lightweight code generation ([LCG](https://learn.microsoft.com/en-us/archive/blogs/joelpob/hello-world-lcg-lightweight-code-gen-style)). This compilation happens during the construction of the object and **heavily** slows it down. In turn, matches using the regular expression are faster. If you do not specify this flag, your regular expression is considered "interpreted". Take this example: ```cs public static void TimeAction(string description, int times, Action func) { // warmup func(); var watch = new Stopwatch(); watch.Start(); for (int i = 0; i < times; i++) { func(); } watch.Stop(); Console.Write(description); Console.WriteLine(" Time Elapsed {0} ms", watch.ElapsedMilliseconds); } static void Main(string[] args) { var simple = "^\\d+$"; var medium = @"^((to|from)\W)?(?<url>http://[\w\.:]+)/questions/(?<questionId>\d+)(/(\w|-)*)?(/(?<answerId>\d+))?"; var complex = @"^(([^<>()[\]\\.,;:\s@""]+" + @"(\.[^<>()[\]\\.,;:\s@""]+)*)|("".+""))@" + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+" + @"[a-zA-Z]{2,}))$"; string[] numbers = new string[] {"1","two", "8378373", "38737", "3873783z"}; string[] emails = new string[] { "sam@sam.com", "sss@s", "sjg@ddd.com.au.au", "onelongemail@oneverylongemail.com" }; foreach (var item in new[] { new {Pattern = simple, Matches = numbers, Name = "Simple number match"}, new {Pattern = medium, Matches = emails, Name = "Simple email match"}, new {Pattern = complex, Matches = emails, Name = "Complex email match"} }) { int i = 0; Regex regex; TimeAction(item.Name + " interpreted uncached single match (x1000)", 1000, () => { regex = new Regex(item.Pattern); regex.Match(item.Matches[i++ % item.Matches.Length]); }); i = 0; TimeAction(item.Name + " compiled uncached single match (x1000)", 1000, () => { regex = new Regex(item.Pattern, RegexOptions.Compiled); regex.Match(item.Matches[i++ % item.Matches.Length]); }); regex = new Regex(item.Pattern); i = 0; TimeAction(item.Name + " prepared interpreted match (x1000000)", 1000000, () => { regex.Match(item.Matches[i++ % item.Matches.Length]); }); regex = new Regex(item.Pattern, RegexOptions.Compiled); i = 0; TimeAction(item.Name + " prepared compiled match (x1000000)", 1000000, () => { regex.Match(item.Matches[i++ % item.Matches.Length]); }); } } ``` It performs 4 tests on 3 different regular expressions. First it tests a **single** once off match (compiled vs non compiled). Second it tests repeat matches that reuse the same regular expression. The results on my machine (compiled in release, no debugger attached) ### 1000 single matches (construct Regex, Match and dispose) ``` Type | Platform | Trivial Number | Simple Email Check | Ext Email Check ------------------------------------------------------------------------------ Interpreted | x86 | 4 ms | 26 ms | 31 ms Interpreted | x64 | 5 ms | 29 ms | 35 ms Compiled | x86 | 913 ms | 3775 ms | 4487 ms Compiled | x64 | 3300 ms | 21985 ms | 22793 ms ``` ### 1,000,000 matches - reusing the Regex object ``` Type | Platform | Trivial Number | Simple Email Check | Ext Email Check ------------------------------------------------------------------------------ Interpreted | x86 | 422 ms | 461 ms | 2122 ms Interpreted | x64 | 436 ms | 463 ms | 2167 ms Compiled | x86 | 279 ms | 166 ms | 1268 ms Compiled | x64 | 281 ms | 176 ms | 1180 ms ``` These results show that compiled regular expressions can be up to **60%** faster for cases where you reuse the `Regex` object. **However** in some cases can be over **3 orders of magnitude** slower to construct. It also shows that the **x64 version** of .NET can be **5 to 6 times slower** when it comes to compilation of regular expressions. --- The recommendation would be to **use the compiled version** in cases where either 1. You do not care about object initialization cost and need the extra performance boost. (note we are talking fractions of a millisecond here) 2. You care a little bit about initialization cost, but are reusing the Regex object so many times that it will compensate for it during your application life cycle. --- ### Spanner in the works, the Regex cache The regular expression engine contains an LRU cache which holds the last 15 regular expressions that were tested using the static methods on the `Regex` class. For example: `Regex.Replace`, `Regex.Match` etc.. all use the Regex cache. The size of the cache can be increased by setting [`Regex.CacheSize`](http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.cachesize.aspx). It accepts changes in size any time during your application's life cycle. New regular expressions are only cached **by the static helpers** on the Regex class. If you construct your objects the cache is checked (for reuse and bumped), however, the regular expression you construct is **not appended to the cache**. This cache is a **trivial** LRU cache, it is implemented using a simple double linked list. If you happen to increase it to 5000, and use 5000 different calls on the static helpers, every regular expression construction will crawl the 5000 entries to see if it has previously been cached. There is a **lock** around the check, so the check can decrease parallelism and introduce thread blocking. The number is set quite low to protect yourself from cases like this, though in some cases you may have no choice but to increase it. My **strong recommendation** would be **never** pass the `RegexOptions.Compiled` option to a static helper. For example: ```cs // WARNING: bad code Regex.IsMatch("10000", @"\\d+", RegexOptions.Compiled) ``` The reason being that you are heavily risking a miss on the LRU cache which will trigger a **super expensive** compile. Additionally, you have no idea what the libraries you depend on are doing, so have little ability to control or predict the **best possible** size of the cache. See also: [BCL team blog](https://blogs.msdn.microsoft.com/bclteam/2010/06/25/optimizing-regular-expression-performance-part-i-working-with-the-regex-class-and-regex-objects-ron-petrusha/) --- **Note** : this is relevant for .NET 2.0 and .NET 4.0. There are some expected changes in 4.5 that may cause this to be revised.
1) [Base Class Library Team on compiled regex](http://blogs.msdn.com/bclteam/archive/2004/11/12/256783.aspx) 2) [Coding Horror, referencing #1 with some good points on the tradeoffs](https://blog.codinghorror.com/to-compile-or-not-to-compile/)
513,417
I have two questions related to the FlashMessenger view helper. Both questions are to do this code: My action method: ``` private $_messages; // set to $this->_helper->FlashMessenger; in init() public function loginAction() { // > login validation < // Switch based on the result code switch ($result->getCode()) { // > snip several cases < case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID: $this->_messages->addMessage("That wasn't the right password."); break; case Zend_Auth_Result::SUCCESS: $this->_messages->addMessage('Logged you in successfully. Welcome back!'); $this->_helper->Redirector('index', 'home'); break; } // >snip< $this->view->messages = $this->_messages->getMessages(); $this->render(); } ``` My layout (Zend\_Layout) view script: ``` <?php if (isset($this->messages) && count($this->messages) > 0) { print_r($this->messages); //$this->partialLoop('partials/messages.phtml', $this->messages); } ?> ``` ### Why is the message not output the first time it is set? I have a feeling this is to do with the messenger being stored in sessions but I'm sure it's to do with my implementation. When I submit a bad value to my form I don't get a message until I either send the form again or refresh. ### What is a good way of sending this to the `PartialLoop` helper? The output of the messenger is something like: ``` Array( [0] => 'Message', [1] => 'Second message' //etc. ) ``` But this is no good for a `PartialLoop` as I need to get the message (which needs each message to be an array, containing a `'message' => 'Message string'` key/value pair). Is there a better method instead of rewriting the array before submitting it to the view?
2009/02/04
[ "https://Stackoverflow.com/questions/513417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
1) [Base Class Library Team on compiled regex](http://blogs.msdn.com/bclteam/archive/2004/11/12/256783.aspx) 2) [Coding Horror, referencing #1 with some good points on the tradeoffs](https://blog.codinghorror.com/to-compile-or-not-to-compile/)
This does not answer the question but I recommend doing this: ``` [RegexGenerator($@"MyPatter")] public partial Regex Regex_SomeRegex(); ``` That way you get best of both worlds. It will be fast at initialization because its created at compile time. And it will also be fast when using it.
513,417
I have two questions related to the FlashMessenger view helper. Both questions are to do this code: My action method: ``` private $_messages; // set to $this->_helper->FlashMessenger; in init() public function loginAction() { // > login validation < // Switch based on the result code switch ($result->getCode()) { // > snip several cases < case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID: $this->_messages->addMessage("That wasn't the right password."); break; case Zend_Auth_Result::SUCCESS: $this->_messages->addMessage('Logged you in successfully. Welcome back!'); $this->_helper->Redirector('index', 'home'); break; } // >snip< $this->view->messages = $this->_messages->getMessages(); $this->render(); } ``` My layout (Zend\_Layout) view script: ``` <?php if (isset($this->messages) && count($this->messages) > 0) { print_r($this->messages); //$this->partialLoop('partials/messages.phtml', $this->messages); } ?> ``` ### Why is the message not output the first time it is set? I have a feeling this is to do with the messenger being stored in sessions but I'm sure it's to do with my implementation. When I submit a bad value to my form I don't get a message until I either send the form again or refresh. ### What is a good way of sending this to the `PartialLoop` helper? The output of the messenger is something like: ``` Array( [0] => 'Message', [1] => 'Second message' //etc. ) ``` But this is no good for a `PartialLoop` as I need to get the message (which needs each message to be an array, containing a `'message' => 'Message string'` key/value pair). Is there a better method instead of rewriting the array before submitting it to the view?
2009/02/04
[ "https://Stackoverflow.com/questions/513417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
`RegexOptions.Compiled` instructs the regular expression engine to compile the regular expression expression into IL using lightweight code generation ([LCG](https://learn.microsoft.com/en-us/archive/blogs/joelpob/hello-world-lcg-lightweight-code-gen-style)). This compilation happens during the construction of the object and **heavily** slows it down. In turn, matches using the regular expression are faster. If you do not specify this flag, your regular expression is considered "interpreted". Take this example: ```cs public static void TimeAction(string description, int times, Action func) { // warmup func(); var watch = new Stopwatch(); watch.Start(); for (int i = 0; i < times; i++) { func(); } watch.Stop(); Console.Write(description); Console.WriteLine(" Time Elapsed {0} ms", watch.ElapsedMilliseconds); } static void Main(string[] args) { var simple = "^\\d+$"; var medium = @"^((to|from)\W)?(?<url>http://[\w\.:]+)/questions/(?<questionId>\d+)(/(\w|-)*)?(/(?<answerId>\d+))?"; var complex = @"^(([^<>()[\]\\.,;:\s@""]+" + @"(\.[^<>()[\]\\.,;:\s@""]+)*)|("".+""))@" + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+" + @"[a-zA-Z]{2,}))$"; string[] numbers = new string[] {"1","two", "8378373", "38737", "3873783z"}; string[] emails = new string[] { "sam@sam.com", "sss@s", "sjg@ddd.com.au.au", "onelongemail@oneverylongemail.com" }; foreach (var item in new[] { new {Pattern = simple, Matches = numbers, Name = "Simple number match"}, new {Pattern = medium, Matches = emails, Name = "Simple email match"}, new {Pattern = complex, Matches = emails, Name = "Complex email match"} }) { int i = 0; Regex regex; TimeAction(item.Name + " interpreted uncached single match (x1000)", 1000, () => { regex = new Regex(item.Pattern); regex.Match(item.Matches[i++ % item.Matches.Length]); }); i = 0; TimeAction(item.Name + " compiled uncached single match (x1000)", 1000, () => { regex = new Regex(item.Pattern, RegexOptions.Compiled); regex.Match(item.Matches[i++ % item.Matches.Length]); }); regex = new Regex(item.Pattern); i = 0; TimeAction(item.Name + " prepared interpreted match (x1000000)", 1000000, () => { regex.Match(item.Matches[i++ % item.Matches.Length]); }); regex = new Regex(item.Pattern, RegexOptions.Compiled); i = 0; TimeAction(item.Name + " prepared compiled match (x1000000)", 1000000, () => { regex.Match(item.Matches[i++ % item.Matches.Length]); }); } } ``` It performs 4 tests on 3 different regular expressions. First it tests a **single** once off match (compiled vs non compiled). Second it tests repeat matches that reuse the same regular expression. The results on my machine (compiled in release, no debugger attached) ### 1000 single matches (construct Regex, Match and dispose) ``` Type | Platform | Trivial Number | Simple Email Check | Ext Email Check ------------------------------------------------------------------------------ Interpreted | x86 | 4 ms | 26 ms | 31 ms Interpreted | x64 | 5 ms | 29 ms | 35 ms Compiled | x86 | 913 ms | 3775 ms | 4487 ms Compiled | x64 | 3300 ms | 21985 ms | 22793 ms ``` ### 1,000,000 matches - reusing the Regex object ``` Type | Platform | Trivial Number | Simple Email Check | Ext Email Check ------------------------------------------------------------------------------ Interpreted | x86 | 422 ms | 461 ms | 2122 ms Interpreted | x64 | 436 ms | 463 ms | 2167 ms Compiled | x86 | 279 ms | 166 ms | 1268 ms Compiled | x64 | 281 ms | 176 ms | 1180 ms ``` These results show that compiled regular expressions can be up to **60%** faster for cases where you reuse the `Regex` object. **However** in some cases can be over **3 orders of magnitude** slower to construct. It also shows that the **x64 version** of .NET can be **5 to 6 times slower** when it comes to compilation of regular expressions. --- The recommendation would be to **use the compiled version** in cases where either 1. You do not care about object initialization cost and need the extra performance boost. (note we are talking fractions of a millisecond here) 2. You care a little bit about initialization cost, but are reusing the Regex object so many times that it will compensate for it during your application life cycle. --- ### Spanner in the works, the Regex cache The regular expression engine contains an LRU cache which holds the last 15 regular expressions that were tested using the static methods on the `Regex` class. For example: `Regex.Replace`, `Regex.Match` etc.. all use the Regex cache. The size of the cache can be increased by setting [`Regex.CacheSize`](http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.cachesize.aspx). It accepts changes in size any time during your application's life cycle. New regular expressions are only cached **by the static helpers** on the Regex class. If you construct your objects the cache is checked (for reuse and bumped), however, the regular expression you construct is **not appended to the cache**. This cache is a **trivial** LRU cache, it is implemented using a simple double linked list. If you happen to increase it to 5000, and use 5000 different calls on the static helpers, every regular expression construction will crawl the 5000 entries to see if it has previously been cached. There is a **lock** around the check, so the check can decrease parallelism and introduce thread blocking. The number is set quite low to protect yourself from cases like this, though in some cases you may have no choice but to increase it. My **strong recommendation** would be **never** pass the `RegexOptions.Compiled` option to a static helper. For example: ```cs // WARNING: bad code Regex.IsMatch("10000", @"\\d+", RegexOptions.Compiled) ``` The reason being that you are heavily risking a miss on the LRU cache which will trigger a **super expensive** compile. Additionally, you have no idea what the libraries you depend on are doing, so have little ability to control or predict the **best possible** size of the cache. See also: [BCL team blog](https://blogs.msdn.microsoft.com/bclteam/2010/06/25/optimizing-regular-expression-performance-part-i-working-with-the-regex-class-and-regex-objects-ron-petrusha/) --- **Note** : this is relevant for .NET 2.0 and .NET 4.0. There are some expected changes in 4.5 that may cause this to be revised.
It should be noted that the performance of regular expressions since .NET 2.0 has been improved with an MRU cache of uncompiled regular expressions. The Regex library code no longer reinterprets the same un-compiled regular expression every time. So there is potentially a bigger performance *penalty* with a compiled and on the fly regular expression. In addition to slower load times, the system also uses more memory to compile the regular expression to opcodes. Essentially, the current advice is either do not compile a regular expression, or compile them in advance to a separate assembly. Ref: BCL Team Blog [Regular Expression performance [David Gutierrez]](http://blogs.msdn.com/bclteam/archive/2004/11/12/256783.aspx)
513,417
I have two questions related to the FlashMessenger view helper. Both questions are to do this code: My action method: ``` private $_messages; // set to $this->_helper->FlashMessenger; in init() public function loginAction() { // > login validation < // Switch based on the result code switch ($result->getCode()) { // > snip several cases < case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID: $this->_messages->addMessage("That wasn't the right password."); break; case Zend_Auth_Result::SUCCESS: $this->_messages->addMessage('Logged you in successfully. Welcome back!'); $this->_helper->Redirector('index', 'home'); break; } // >snip< $this->view->messages = $this->_messages->getMessages(); $this->render(); } ``` My layout (Zend\_Layout) view script: ``` <?php if (isset($this->messages) && count($this->messages) > 0) { print_r($this->messages); //$this->partialLoop('partials/messages.phtml', $this->messages); } ?> ``` ### Why is the message not output the first time it is set? I have a feeling this is to do with the messenger being stored in sessions but I'm sure it's to do with my implementation. When I submit a bad value to my form I don't get a message until I either send the form again or refresh. ### What is a good way of sending this to the `PartialLoop` helper? The output of the messenger is something like: ``` Array( [0] => 'Message', [1] => 'Second message' //etc. ) ``` But this is no good for a `PartialLoop` as I need to get the message (which needs each message to be an array, containing a `'message' => 'Message string'` key/value pair). Is there a better method instead of rewriting the array before submitting it to the view?
2009/02/04
[ "https://Stackoverflow.com/questions/513417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
It should be noted that the performance of regular expressions since .NET 2.0 has been improved with an MRU cache of uncompiled regular expressions. The Regex library code no longer reinterprets the same un-compiled regular expression every time. So there is potentially a bigger performance *penalty* with a compiled and on the fly regular expression. In addition to slower load times, the system also uses more memory to compile the regular expression to opcodes. Essentially, the current advice is either do not compile a regular expression, or compile them in advance to a separate assembly. Ref: BCL Team Blog [Regular Expression performance [David Gutierrez]](http://blogs.msdn.com/bclteam/archive/2004/11/12/256783.aspx)
This does not answer the question but I recommend doing this: ``` [RegexGenerator($@"MyPatter")] public partial Regex Regex_SomeRegex(); ``` That way you get best of both worlds. It will be fast at initialization because its created at compile time. And it will also be fast when using it.
513,417
I have two questions related to the FlashMessenger view helper. Both questions are to do this code: My action method: ``` private $_messages; // set to $this->_helper->FlashMessenger; in init() public function loginAction() { // > login validation < // Switch based on the result code switch ($result->getCode()) { // > snip several cases < case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID: $this->_messages->addMessage("That wasn't the right password."); break; case Zend_Auth_Result::SUCCESS: $this->_messages->addMessage('Logged you in successfully. Welcome back!'); $this->_helper->Redirector('index', 'home'); break; } // >snip< $this->view->messages = $this->_messages->getMessages(); $this->render(); } ``` My layout (Zend\_Layout) view script: ``` <?php if (isset($this->messages) && count($this->messages) > 0) { print_r($this->messages); //$this->partialLoop('partials/messages.phtml', $this->messages); } ?> ``` ### Why is the message not output the first time it is set? I have a feeling this is to do with the messenger being stored in sessions but I'm sure it's to do with my implementation. When I submit a bad value to my form I don't get a message until I either send the form again or refresh. ### What is a good way of sending this to the `PartialLoop` helper? The output of the messenger is something like: ``` Array( [0] => 'Message', [1] => 'Second message' //etc. ) ``` But this is no good for a `PartialLoop` as I need to get the message (which needs each message to be an array, containing a `'message' => 'Message string'` key/value pair). Is there a better method instead of rewriting the array before submitting it to the view?
2009/02/04
[ "https://Stackoverflow.com/questions/513417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
`RegexOptions.Compiled` instructs the regular expression engine to compile the regular expression expression into IL using lightweight code generation ([LCG](https://learn.microsoft.com/en-us/archive/blogs/joelpob/hello-world-lcg-lightweight-code-gen-style)). This compilation happens during the construction of the object and **heavily** slows it down. In turn, matches using the regular expression are faster. If you do not specify this flag, your regular expression is considered "interpreted". Take this example: ```cs public static void TimeAction(string description, int times, Action func) { // warmup func(); var watch = new Stopwatch(); watch.Start(); for (int i = 0; i < times; i++) { func(); } watch.Stop(); Console.Write(description); Console.WriteLine(" Time Elapsed {0} ms", watch.ElapsedMilliseconds); } static void Main(string[] args) { var simple = "^\\d+$"; var medium = @"^((to|from)\W)?(?<url>http://[\w\.:]+)/questions/(?<questionId>\d+)(/(\w|-)*)?(/(?<answerId>\d+))?"; var complex = @"^(([^<>()[\]\\.,;:\s@""]+" + @"(\.[^<>()[\]\\.,;:\s@""]+)*)|("".+""))@" + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+" + @"[a-zA-Z]{2,}))$"; string[] numbers = new string[] {"1","two", "8378373", "38737", "3873783z"}; string[] emails = new string[] { "sam@sam.com", "sss@s", "sjg@ddd.com.au.au", "onelongemail@oneverylongemail.com" }; foreach (var item in new[] { new {Pattern = simple, Matches = numbers, Name = "Simple number match"}, new {Pattern = medium, Matches = emails, Name = "Simple email match"}, new {Pattern = complex, Matches = emails, Name = "Complex email match"} }) { int i = 0; Regex regex; TimeAction(item.Name + " interpreted uncached single match (x1000)", 1000, () => { regex = new Regex(item.Pattern); regex.Match(item.Matches[i++ % item.Matches.Length]); }); i = 0; TimeAction(item.Name + " compiled uncached single match (x1000)", 1000, () => { regex = new Regex(item.Pattern, RegexOptions.Compiled); regex.Match(item.Matches[i++ % item.Matches.Length]); }); regex = new Regex(item.Pattern); i = 0; TimeAction(item.Name + " prepared interpreted match (x1000000)", 1000000, () => { regex.Match(item.Matches[i++ % item.Matches.Length]); }); regex = new Regex(item.Pattern, RegexOptions.Compiled); i = 0; TimeAction(item.Name + " prepared compiled match (x1000000)", 1000000, () => { regex.Match(item.Matches[i++ % item.Matches.Length]); }); } } ``` It performs 4 tests on 3 different regular expressions. First it tests a **single** once off match (compiled vs non compiled). Second it tests repeat matches that reuse the same regular expression. The results on my machine (compiled in release, no debugger attached) ### 1000 single matches (construct Regex, Match and dispose) ``` Type | Platform | Trivial Number | Simple Email Check | Ext Email Check ------------------------------------------------------------------------------ Interpreted | x86 | 4 ms | 26 ms | 31 ms Interpreted | x64 | 5 ms | 29 ms | 35 ms Compiled | x86 | 913 ms | 3775 ms | 4487 ms Compiled | x64 | 3300 ms | 21985 ms | 22793 ms ``` ### 1,000,000 matches - reusing the Regex object ``` Type | Platform | Trivial Number | Simple Email Check | Ext Email Check ------------------------------------------------------------------------------ Interpreted | x86 | 422 ms | 461 ms | 2122 ms Interpreted | x64 | 436 ms | 463 ms | 2167 ms Compiled | x86 | 279 ms | 166 ms | 1268 ms Compiled | x64 | 281 ms | 176 ms | 1180 ms ``` These results show that compiled regular expressions can be up to **60%** faster for cases where you reuse the `Regex` object. **However** in some cases can be over **3 orders of magnitude** slower to construct. It also shows that the **x64 version** of .NET can be **5 to 6 times slower** when it comes to compilation of regular expressions. --- The recommendation would be to **use the compiled version** in cases where either 1. You do not care about object initialization cost and need the extra performance boost. (note we are talking fractions of a millisecond here) 2. You care a little bit about initialization cost, but are reusing the Regex object so many times that it will compensate for it during your application life cycle. --- ### Spanner in the works, the Regex cache The regular expression engine contains an LRU cache which holds the last 15 regular expressions that were tested using the static methods on the `Regex` class. For example: `Regex.Replace`, `Regex.Match` etc.. all use the Regex cache. The size of the cache can be increased by setting [`Regex.CacheSize`](http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.cachesize.aspx). It accepts changes in size any time during your application's life cycle. New regular expressions are only cached **by the static helpers** on the Regex class. If you construct your objects the cache is checked (for reuse and bumped), however, the regular expression you construct is **not appended to the cache**. This cache is a **trivial** LRU cache, it is implemented using a simple double linked list. If you happen to increase it to 5000, and use 5000 different calls on the static helpers, every regular expression construction will crawl the 5000 entries to see if it has previously been cached. There is a **lock** around the check, so the check can decrease parallelism and introduce thread blocking. The number is set quite low to protect yourself from cases like this, though in some cases you may have no choice but to increase it. My **strong recommendation** would be **never** pass the `RegexOptions.Compiled` option to a static helper. For example: ```cs // WARNING: bad code Regex.IsMatch("10000", @"\\d+", RegexOptions.Compiled) ``` The reason being that you are heavily risking a miss on the LRU cache which will trigger a **super expensive** compile. Additionally, you have no idea what the libraries you depend on are doing, so have little ability to control or predict the **best possible** size of the cache. See also: [BCL team blog](https://blogs.msdn.microsoft.com/bclteam/2010/06/25/optimizing-regular-expression-performance-part-i-working-with-the-regex-class-and-regex-objects-ron-petrusha/) --- **Note** : this is relevant for .NET 2.0 and .NET 4.0. There are some expected changes in 4.5 that may cause this to be revised.
This does not answer the question but I recommend doing this: ``` [RegexGenerator($@"MyPatter")] public partial Regex Regex_SomeRegex(); ``` That way you get best of both worlds. It will be fast at initialization because its created at compile time. And it will also be fast when using it.
23,063
Today we had a probational exam in analysis. I wasn't able to solve one of the exercises and I have no idea what theorem to apply in order to solve it: Let $I=[0,1]$ and $f: I \rightarrow \mathbb{R}$ be continuously differentiable. Assuming that $f$ has a root. Show: $$\max\_{x \in I} |f(x)| \leq \max\_{x \in I} |f'(x)|$$ Does this theorem have a name? What other theorem will I need in order to prove it? I'm sure the fact that the function has a root is important, but I don't see why and how to make use of it... Thanks for your help!
2011/02/21
[ "https://math.stackexchange.com/questions/23063", "https://math.stackexchange.com", "https://math.stackexchange.com/users/3787/" ]
The example $f(x)\equiv 1$ shows that having a root is important. Let $x\_0\in I$ be such that $|f(x\_0)|=\max\_{x\in I}|f(x)|$, and let $r\in I$ be such that $f(r)=0$. Then $\left|\frac{f(x\_0)-f(r)}{x\_0-r}\right|\geq |f(x\_0)|$, and you can apply the Mean Value Theorem to finish. Continuity of the derivative isn't necessary, just continuity of $f$ on $I$ and differentiability on $(0,1)$, except that with continuity of $f'$ you can really say that the right-hand side of the inequality is a max rather than a sup.
I don't know if this theorem has a name, but you're guessing right that it is important that $f$ has a root (otherwise adding a constant allows you to make the values of $f$ arbitrarily large without changing $f'$). One proof is a straightforward application of the fundamental theorem of analysis and a standard estimate on the integral. Indeed, if $x\_{0}$ is such that $f(x\_{0}) = 0$ then $f(x) = \int\_{x\_{0}}^{x} f'(t)\,dt$. Now combine this with the fact that $|\int\_{a}^{b} h| \leq \int\_{a}^{b}|h|$ for all $a,b$ and all integrable $h$.
23,063
Today we had a probational exam in analysis. I wasn't able to solve one of the exercises and I have no idea what theorem to apply in order to solve it: Let $I=[0,1]$ and $f: I \rightarrow \mathbb{R}$ be continuously differentiable. Assuming that $f$ has a root. Show: $$\max\_{x \in I} |f(x)| \leq \max\_{x \in I} |f'(x)|$$ Does this theorem have a name? What other theorem will I need in order to prove it? I'm sure the fact that the function has a root is important, but I don't see why and how to make use of it... Thanks for your help!
2011/02/21
[ "https://math.stackexchange.com/questions/23063", "https://math.stackexchange.com", "https://math.stackexchange.com/users/3787/" ]
The example $f(x)\equiv 1$ shows that having a root is important. Let $x\_0\in I$ be such that $|f(x\_0)|=\max\_{x\in I}|f(x)|$, and let $r\in I$ be such that $f(r)=0$. Then $\left|\frac{f(x\_0)-f(r)}{x\_0-r}\right|\geq |f(x\_0)|$, and you can apply the Mean Value Theorem to finish. Continuity of the derivative isn't necessary, just continuity of $f$ on $I$ and differentiability on $(0,1)$, except that with continuity of $f'$ you can really say that the right-hand side of the inequality is a max rather than a sup.
Hints: Mean value theorem between a root and any point + the fact that the diameter of $I$ is $1$. By the way, continuity on the closed interval $I$ and differentiability on the interior of $I$ are sufficient.
23,063
Today we had a probational exam in analysis. I wasn't able to solve one of the exercises and I have no idea what theorem to apply in order to solve it: Let $I=[0,1]$ and $f: I \rightarrow \mathbb{R}$ be continuously differentiable. Assuming that $f$ has a root. Show: $$\max\_{x \in I} |f(x)| \leq \max\_{x \in I} |f'(x)|$$ Does this theorem have a name? What other theorem will I need in order to prove it? I'm sure the fact that the function has a root is important, but I don't see why and how to make use of it... Thanks for your help!
2011/02/21
[ "https://math.stackexchange.com/questions/23063", "https://math.stackexchange.com", "https://math.stackexchange.com/users/3787/" ]
I don't know if this theorem has a name, but you're guessing right that it is important that $f$ has a root (otherwise adding a constant allows you to make the values of $f$ arbitrarily large without changing $f'$). One proof is a straightforward application of the fundamental theorem of analysis and a standard estimate on the integral. Indeed, if $x\_{0}$ is such that $f(x\_{0}) = 0$ then $f(x) = \int\_{x\_{0}}^{x} f'(t)\,dt$. Now combine this with the fact that $|\int\_{a}^{b} h| \leq \int\_{a}^{b}|h|$ for all $a,b$ and all integrable $h$.
Hints: Mean value theorem between a root and any point + the fact that the diameter of $I$ is $1$. By the way, continuity on the closed interval $I$ and differentiability on the interior of $I$ are sufficient.
25,897,207
I'm working on a piece of javascript that sets a color value based on the status of a healthcheck. The string color values tie into the CSS I'm working with, and the string statuses tie into the health checks reported to this script. This function is designed to set the color value for each healthcheck, AND return an overall status of the system. The overall status should be correspond to the worst condition health check (e.g. if most are "ok", and one is "fatal", overall should be "danger"). The current code works to set individual color values, but not the overall. Is there an "elegant" way to set the overall without having to use lots of nested if statements? ``` function getStatus(checks) { var overall = ''; for (j in checks) { checks[j]['color'] = ''; switch (checks[j].status) { case 'OK': checks[j]['color'] = 'success'; break; case 'INFO': checks[j]['color'] = 'info'; break; case 'WARN': checks[j]['color'] = 'warning'; break; case 'ERROR': checks[j]['color'] = 'danger'; break; case 'FATAL': checks[j]['color'] = 'danger'; break; } } return overall; } ``` I could do something like this: ``` case 'WARN': if (overall === "OK" || overall === "INFO") { overall = 'warning'; } ``` ... but that gets messy, especially when checking for "ERROR" which must be greater than 3 values, but less than one. Is there a more effective way?
2014/09/17
[ "https://Stackoverflow.com/questions/25897207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3570747/" ]
Well there's no other choice ? But some improvements are possible. Add another for loop + a switch. If there's an error somewhere, you don't need to continue the loop and you can return 'danger' ``` overall = 'success' for (j in checks) { switch (checks[j].status) { case 'OK': break; case 'INFO': if (overall === 'success') overall = 'info' break; case 'WARN': if (overall === 'success' || overall === 'warning') overall = 'warning' break; case 'ERROR': case 'FATAL': return 'danger' } } ```
Use numbers instead of strings and then (if I've understood what you're trying to do) its simply a case of returning the highest status you receive. You can use an associative array to store the string representation, error code and color for each status in separate objects and move those around (with the advantage that you can bin off that switch statement): ``` var statuses = { ok: { code: 1, status: 'OK', color: 'success'}, info: { code: 2, status: 'INFO', color: 'info'}, warn: { code: 3, status: 'WARN', color: 'warning'}, error: { code: 4, status: 'ERROR', color: 'danger'}, fatal: { code: 5, status: 'FATAL', color: 'danger'}, } // example checks var checks = [statuses['ok'], statuses['warn'], statuses['fatal']]; function getStatus(checks) { var overall = statuses['ok']; for (check in checks) { if (check.code > overall.code) { overall = check; } } return overall; } ```
25,897,207
I'm working on a piece of javascript that sets a color value based on the status of a healthcheck. The string color values tie into the CSS I'm working with, and the string statuses tie into the health checks reported to this script. This function is designed to set the color value for each healthcheck, AND return an overall status of the system. The overall status should be correspond to the worst condition health check (e.g. if most are "ok", and one is "fatal", overall should be "danger"). The current code works to set individual color values, but not the overall. Is there an "elegant" way to set the overall without having to use lots of nested if statements? ``` function getStatus(checks) { var overall = ''; for (j in checks) { checks[j]['color'] = ''; switch (checks[j].status) { case 'OK': checks[j]['color'] = 'success'; break; case 'INFO': checks[j]['color'] = 'info'; break; case 'WARN': checks[j]['color'] = 'warning'; break; case 'ERROR': checks[j]['color'] = 'danger'; break; case 'FATAL': checks[j]['color'] = 'danger'; break; } } return overall; } ``` I could do something like this: ``` case 'WARN': if (overall === "OK" || overall === "INFO") { overall = 'warning'; } ``` ... but that gets messy, especially when checking for "ERROR" which must be greater than 3 values, but less than one. Is there a more effective way?
2014/09/17
[ "https://Stackoverflow.com/questions/25897207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3570747/" ]
Use numbers instead of strings and then (if I've understood what you're trying to do) its simply a case of returning the highest status you receive. You can use an associative array to store the string representation, error code and color for each status in separate objects and move those around (with the advantage that you can bin off that switch statement): ``` var statuses = { ok: { code: 1, status: 'OK', color: 'success'}, info: { code: 2, status: 'INFO', color: 'info'}, warn: { code: 3, status: 'WARN', color: 'warning'}, error: { code: 4, status: 'ERROR', color: 'danger'}, fatal: { code: 5, status: 'FATAL', color: 'danger'}, } // example checks var checks = [statuses['ok'], statuses['warn'], statuses['fatal']]; function getStatus(checks) { var overall = statuses['ok']; for (check in checks) { if (check.code > overall.code) { overall = check; } } return overall; } ```
Following net.uk.sweet's answer, you might want to define an [enum](https://stackoverflow.com/questions/287903/enums-in-javascript) to store the values of status ``` medical.status = { INFO : 0, OK : 1, WARNING : 2, DANGER : 3, FATAL : 4 } ``` And in the rest of your code, instead of giving string values to `checks[j]`, you should assign one of these constants : ``` checks[j].status = medical.status.DANGER ``` Then you can use the < operator just like in net.uk.sweet's answer
25,897,207
I'm working on a piece of javascript that sets a color value based on the status of a healthcheck. The string color values tie into the CSS I'm working with, and the string statuses tie into the health checks reported to this script. This function is designed to set the color value for each healthcheck, AND return an overall status of the system. The overall status should be correspond to the worst condition health check (e.g. if most are "ok", and one is "fatal", overall should be "danger"). The current code works to set individual color values, but not the overall. Is there an "elegant" way to set the overall without having to use lots of nested if statements? ``` function getStatus(checks) { var overall = ''; for (j in checks) { checks[j]['color'] = ''; switch (checks[j].status) { case 'OK': checks[j]['color'] = 'success'; break; case 'INFO': checks[j]['color'] = 'info'; break; case 'WARN': checks[j]['color'] = 'warning'; break; case 'ERROR': checks[j]['color'] = 'danger'; break; case 'FATAL': checks[j]['color'] = 'danger'; break; } } return overall; } ``` I could do something like this: ``` case 'WARN': if (overall === "OK" || overall === "INFO") { overall = 'warning'; } ``` ... but that gets messy, especially when checking for "ERROR" which must be greater than 3 values, but less than one. Is there a more effective way?
2014/09/17
[ "https://Stackoverflow.com/questions/25897207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3570747/" ]
Well there's no other choice ? But some improvements are possible. Add another for loop + a switch. If there's an error somewhere, you don't need to continue the loop and you can return 'danger' ``` overall = 'success' for (j in checks) { switch (checks[j].status) { case 'OK': break; case 'INFO': if (overall === 'success') overall = 'info' break; case 'WARN': if (overall === 'success' || overall === 'warning') overall = 'warning' break; case 'ERROR': case 'FATAL': return 'danger' } } ```
Following net.uk.sweet's answer, you might want to define an [enum](https://stackoverflow.com/questions/287903/enums-in-javascript) to store the values of status ``` medical.status = { INFO : 0, OK : 1, WARNING : 2, DANGER : 3, FATAL : 4 } ``` And in the rest of your code, instead of giving string values to `checks[j]`, you should assign one of these constants : ``` checks[j].status = medical.status.DANGER ``` Then you can use the < operator just like in net.uk.sweet's answer
37,542,149
I implemented Google Cloud Messaging in my Android app. When I send a message with JSON while I have opened the app, it acts different than when I have the app closed. When I have the app **open**, and receive the notification, it starts the intent I want it to start. When I have the app **closed** when i receive the notification, and I click on the notification, it opens the Main intent. How can I say which intent it needs to open when I have closed my app and receive the push notification? *The code in MyGcmListenerService* ``` public class MyGcmListenerService extends GcmListenerService { private static final String TAG = "MyGcmListenerService"; File fileDir, file; String filename, filestring; /** * Called when message is received. * * @param from SenderID of the sender. * @param data Data bundle containing message data as key/value pairs. * For Set of keys use data.keySet(). */ @Override public void onMessageReceived(String from, Bundle data) { Bundle notification = data.getBundle("notification"); String title = notification.getString("title"); String naam = notification.getString("naam"); String nfcId = notification.getString("nfcId"); Log.d(TAG, "From: " + from); Log.d(TAG, "Title: " + title); Log.d(TAG, "Naam: " + naam); Log.d(TAG, "nfcId: " + nfcId); if (from.startsWith("/topics/")) { } else { filename = "gegevensOverledene"; ReadWriteFile readWriteFile = new ReadWriteFile(getApplicationContext()); readWriteFile.writeFileOverledene(filename, naam); } sendNotification(title, naam, nfcId); } /** * Create and show a simple notification containing the received GCM message. */ private void sendNotification(String title, String naam, String nfcId) { Intent intent = new Intent(this, PinLoginActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra("naam", naam); intent.putExtra("nfcId",nfcId); intent.putExtra("Class",NieuweOverledeneActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle(title) .setContentText(naam) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); } } ``` *The JSON I send, note that I left out the token\_mobile on purpose* ``` { "to": "TOKEN_MOBILE****************", "notification": { "title": "Nieuwe overledene", "body": "Henk", "naam": "Henk", "nfcId": "80-40-A3-4A-C2-D6-04" } } ```
2016/05/31
[ "https://Stackoverflow.com/questions/37542149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2387111/" ]
You are sending a notification message. See more on how notification messages are to be handled [here](https://firebase.google.com/docs/cloud-messaging/downstream#sample-receive). When your app is in the foreground notification messages are passed to your `onMessageReceived` callback. There you can decide what should be done with the received message, eg: generate and display a notification or sync with your app server or whatever. When your app is in the background notification messages automatically generate notifications based on the properties passed in the "notification" object of your downstream message request, `onMessageReceived` **is not called in this case**. If you look at the [reference docs](https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support) for notification messages you will see a field named `click_action` you can use this to define what Activity is launched when the automatically generated notification is tapped: > > On Android, if this is set, an activity with a matching intent filter > is launched when user clicks the notification. > > > If this is not set the main Activity is launched, which is what you are seeing now. **Note:** This behaviour is only for Notification Messages, if you send data only messages then all sent messages will result in `onMessageReceived` being called.
check Following ``` /** * Create and show a simple notification containing the received GCM message. */ private void sendNotification(String title, String naam, String nfcId) { //Create the intent according to your condition and pass it to pendingintent. Intent intent = new Intent(this, PinLoginActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra("naam", naam); intent.putExtra("nfcId",nfcId); intent.putExtra("Class",NieuweOverledeneActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle(title) .setContentText(naam) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); } ```
8,256,864
When I write a new exception type, am I supposed to write only the constructors needed, or implement all constructors exisiting in `Throwable` (and calling them by `super()`)? When thinking about it, I would say implement only what is needed (YAGNI - You Ain't Gonna Need It). If I need another constructor later, I just add it. Example: ``` public void MyException extends RuntimeException { // I only need this constructor public MyException(Throwable cause) { super(cause); } } ```
2011/11/24
[ "https://Stackoverflow.com/questions/8256864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1178669/" ]
Only implement what you'll need and add as you need them. I usually add the one with the String message and the one you have (for wrapping another Exception).
Yes, you should implement just the ones you are going to need. Systems around that I work/worked wich, usually implements at least a constructor that receives the exception cause (exactly like your example). Also an exception defining only a default constructor won't do make much sense unless it's something very very very specific. Best regards.
8,256,864
When I write a new exception type, am I supposed to write only the constructors needed, or implement all constructors exisiting in `Throwable` (and calling them by `super()`)? When thinking about it, I would say implement only what is needed (YAGNI - You Ain't Gonna Need It). If I need another constructor later, I just add it. Example: ``` public void MyException extends RuntimeException { // I only need this constructor public MyException(Throwable cause) { super(cause); } } ```
2011/11/24
[ "https://Stackoverflow.com/questions/8256864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1178669/" ]
Only implement what you'll need and add as you need them. I usually add the one with the String message and the one you have (for wrapping another Exception).
It depends what you are writing for. For a small program, do not write dead code. If the class is going into a library or will be used by other team/team-members where there is some kind of code ownership going on, then write the complete class. Be careful with this: "speculative generalisation" is a serious problem in software development.
8,256,864
When I write a new exception type, am I supposed to write only the constructors needed, or implement all constructors exisiting in `Throwable` (and calling them by `super()`)? When thinking about it, I would say implement only what is needed (YAGNI - You Ain't Gonna Need It). If I need another constructor later, I just add it. Example: ``` public void MyException extends RuntimeException { // I only need this constructor public MyException(Throwable cause) { super(cause); } } ```
2011/11/24
[ "https://Stackoverflow.com/questions/8256864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1178669/" ]
It depends what you are writing for. For a small program, do not write dead code. If the class is going into a library or will be used by other team/team-members where there is some kind of code ownership going on, then write the complete class. Be careful with this: "speculative generalisation" is a serious problem in software development.
Yes, you should implement just the ones you are going to need. Systems around that I work/worked wich, usually implements at least a constructor that receives the exception cause (exactly like your example). Also an exception defining only a default constructor won't do make much sense unless it's something very very very specific. Best regards.
171,144
[![here](https://i.stack.imgur.com/fAp3Q.gif)](https://i.stack.imgur.com/fAp3Q.gif) (source: [nde-ed.org](https://www.nde-ed.org/EducationResources/CommunityCollege/RadiationSafety/Graphics/elec_mag_field.gif)) The above diagram shows an electromagnetic wave propogating in the $x$ direction, if the electric field is in the $y$ direction and the magnetic in the $z$ direction. I was taught however that the strength of an electric field is given by the 'density' of field lines in a region, and in the above graphic it seems that the density is always the same, but that the area the electric field occupies changes. This implies that the strength of the electric field along the x axis never really changes, but it just spreads into the y axis. But then I thought perhaps it is not the space that the electric field occupies that changes, but the magnitude of the electric field, with this being the only way to show it graphically. So is an electromagnetic field just a single beam on the x axis with varying magnitudes of E and B, or does it extend into the y and z directions?
2015/03/19
[ "https://physics.stackexchange.com/questions/171144", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/60080/" ]
Your last paragraph is right. The vectors in that picture are not really taking up a certain amount of space; they are simply vectors that exist only a the very base of where they are drawn. Their units are units of electric and magnetic field strength, not of length. We simply draw them as vectors pointing through a certain amount of space because we don't have a way of representing the entire vector all at one point. An electromagnetic field extends all throughout space. The ideal picture would show electric and magnetic field vectors all over the place, one pair of vectors at every single point in space. Again, we simply don't know how to draw the electric field at every single point all at the same time. But for a plane wave, you can imagine that at any value of y and z there is a wave doing exactly the same thing as the one shown. When trying to draw the entire electric field, we normally use field lines instead of drawing a whole lot of vectors. Both type of pictures - vectors and field lines - can help with your intuition.
> > So is an electromagnetic field just a single beam on the x axis with varying magnitudes of E and B, or does it extend into the y and z directions? > > > The EM field extends in all directions and for most intents and purposes is omnipresent. If it helps, you can imagine the electromagnetic field as a bundles of field lines, but it's not vital for this question. An electromagnetic wave however, is a propagating disturbance in the electromagnetic field. If you imagine pressure waves in the air, you could draw a diagram relating spatial position to air pressure - the diagram shown is basically the same concept, but with electric and magnetic potentials instead of pressure.
50,549,935
I have a very large dataset in R with 1797 observations (rows) and 24 variables (columns) corresponding to a survey conducted through EPFL community. The respondents were asked at which frequency they perform 23 pro-environmental behaviours and they answered on a relative scale, leading to a score between 1 (for never) and 5 (for very often). [![enter image description here](https://i.stack.imgur.com/lq54a.png)](https://i.stack.imgur.com/lq54a.png) I would like to check for duplicated values inside each row in order to see if people answered randomly of seriously (e.g., someone having a lot of "3" values). Therefore, I want to retrieve these duplicates per row, do you have an idea of how I can do that? Thanks :)
2018/05/27
[ "https://Stackoverflow.com/questions/50549935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9853621/" ]
You can use the `tidyverse` approach. Sample data: ``` set.seed(123) df <- data.frame(id = c(1:5), q1 = sample(1:5, 5, replace = TRUE), q2 = sample(1:5, 5, replace = TRUE), q3 = sample(1:5, 5, replace = TRUE), q4 = sample(1:5, 5, replace = TRUE), q5 = sample(1:5, 5, replace = TRUE), q6 = sample(1:5, 5, replace = TRUE), q7 = sample(1:5, 5, replace = TRUE), q8 = sample(1:5, 5, replace = TRUE), q9 = sample(1:5, 5, replace = TRUE), q10 = sample(1:5, 5, replace = TRUE)) require(tidyverse) df %>% gather(question, value, -id) %>% group_by(id) %>% #Give you the count for each answer count(value) %>% ungroup() %>% #In addition, you can calculate the prop. of the same answer out of the 10 questions. mutate(prop = n / 10) ``` Output: ``` id value n prop 1 1 1 3 0.3 2 1 2 1 0.1 3 1 3 1 0.1 4 1 4 1 0.1 5 1 5 4 0.4 6 2 2 2 0.2 7 2 3 4 0.4 8 2 4 3 0.3 9 2 5 1 0.1 10 3 1 1 0.1 11 3 2 1 0.1 12 3 3 4 0.4 13 3 4 3 0.3 14 3 5 1 0.1 15 4 2 5 0.5 16 4 3 2 0.2 17 4 4 1 0.1 18 4 5 2 0.2 19 5 1 4 0.4 20 5 2 1 0.1 21 5 3 1 0.1 22 5 4 1 0.1 23 5 5 3 0.3 ```
To find duplicated elements in row: ``` duplicated(x) ``` > > Example vector: `x <- c(1, 1, 4, 5, 4, 6)` > > > Result: `[1] FALSE TRUE FALSE FALSE TRUE FALSE` > > > To extract duplicated elements: ``` x[duplicated(x)] ``` > > Example vector: `x <- c(1, 1, 4, 5, 4, 6)` > > > Result: `[1] 1 4` > > > Useful sources: [R duplicated function manual](https://stat.ethz.ch/R-manual/R-devel/library/base/html/duplicated.html) [Duplicated function examples](http://www.sthda.com/english/wiki/identifying-and-removing-duplicate-data-in-r)
50,549,935
I have a very large dataset in R with 1797 observations (rows) and 24 variables (columns) corresponding to a survey conducted through EPFL community. The respondents were asked at which frequency they perform 23 pro-environmental behaviours and they answered on a relative scale, leading to a score between 1 (for never) and 5 (for very often). [![enter image description here](https://i.stack.imgur.com/lq54a.png)](https://i.stack.imgur.com/lq54a.png) I would like to check for duplicated values inside each row in order to see if people answered randomly of seriously (e.g., someone having a lot of "3" values). Therefore, I want to retrieve these duplicates per row, do you have an idea of how I can do that? Thanks :)
2018/05/27
[ "https://Stackoverflow.com/questions/50549935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9853621/" ]
To find duplicated elements in row: ``` duplicated(x) ``` > > Example vector: `x <- c(1, 1, 4, 5, 4, 6)` > > > Result: `[1] FALSE TRUE FALSE FALSE TRUE FALSE` > > > To extract duplicated elements: ``` x[duplicated(x)] ``` > > Example vector: `x <- c(1, 1, 4, 5, 4, 6)` > > > Result: `[1] 1 4` > > > Useful sources: [R duplicated function manual](https://stat.ethz.ch/R-manual/R-devel/library/base/html/duplicated.html) [Duplicated function examples](http://www.sthda.com/english/wiki/identifying-and-removing-duplicate-data-in-r)
Using DJV's sample data, we can find the mode for each row, then compute the ratio of use of this value : ``` modes <- as.numeric(apply(df[-1],1,function(x) names(sort(-table(x)))[1])) ratios <- rowSums(df[-1]==modes)/(ncol(df)-1) # or df$ratios <-... to store it in a new col # [1] 0.4 0.4 0.4 0.5 0.4 ```
50,549,935
I have a very large dataset in R with 1797 observations (rows) and 24 variables (columns) corresponding to a survey conducted through EPFL community. The respondents were asked at which frequency they perform 23 pro-environmental behaviours and they answered on a relative scale, leading to a score between 1 (for never) and 5 (for very often). [![enter image description here](https://i.stack.imgur.com/lq54a.png)](https://i.stack.imgur.com/lq54a.png) I would like to check for duplicated values inside each row in order to see if people answered randomly of seriously (e.g., someone having a lot of "3" values). Therefore, I want to retrieve these duplicates per row, do you have an idea of how I can do that? Thanks :)
2018/05/27
[ "https://Stackoverflow.com/questions/50549935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9853621/" ]
You can use the `tidyverse` approach. Sample data: ``` set.seed(123) df <- data.frame(id = c(1:5), q1 = sample(1:5, 5, replace = TRUE), q2 = sample(1:5, 5, replace = TRUE), q3 = sample(1:5, 5, replace = TRUE), q4 = sample(1:5, 5, replace = TRUE), q5 = sample(1:5, 5, replace = TRUE), q6 = sample(1:5, 5, replace = TRUE), q7 = sample(1:5, 5, replace = TRUE), q8 = sample(1:5, 5, replace = TRUE), q9 = sample(1:5, 5, replace = TRUE), q10 = sample(1:5, 5, replace = TRUE)) require(tidyverse) df %>% gather(question, value, -id) %>% group_by(id) %>% #Give you the count for each answer count(value) %>% ungroup() %>% #In addition, you can calculate the prop. of the same answer out of the 10 questions. mutate(prop = n / 10) ``` Output: ``` id value n prop 1 1 1 3 0.3 2 1 2 1 0.1 3 1 3 1 0.1 4 1 4 1 0.1 5 1 5 4 0.4 6 2 2 2 0.2 7 2 3 4 0.4 8 2 4 3 0.3 9 2 5 1 0.1 10 3 1 1 0.1 11 3 2 1 0.1 12 3 3 4 0.4 13 3 4 3 0.3 14 3 5 1 0.1 15 4 2 5 0.5 16 4 3 2 0.2 17 4 4 1 0.1 18 4 5 2 0.2 19 5 1 4 0.4 20 5 2 1 0.1 21 5 3 1 0.1 22 5 4 1 0.1 23 5 5 3 0.3 ```
I guess the just want to count how often the questions were answered with the same value (no matter which question). This does it: ``` library(reshape2) data <- data.frame(ID = c(1, 2), Q1 = c(1, 4), Q2 = c(5, 2), Q3 = c(3, 2), Q4 = c(5, 2)) data # ID Q1 Q2 Q3 Q4 # 1 1 1 5 3 5 # 2 2 4 2 2 2 melted.data <- melt(data, "ID") # , measure.vars = "") melted.data melted.data$count <- 1 melted.data # "variable" contains the original column name now, "value" the cell content # ID variable value count # 1 1 Q1 1 1 # 2 2 Q1 4 1 # 3 1 Q2 5 1 # 4 2 Q2 2 1 # 5 1 Q3 3 1 # 6 2 Q3 2 1 # 7 1 Q4 5 1 # 8 2 Q4 2 1 # group by "ID" + "value" columns and calculate the sum for the column "count" # (I hate the "aggregate" syntax ;-) aggregate( count ~ ID + value, data = melted.data, sum) ID value count # 1 1 1 1 # 2 2 2 3 # 3 1 3 1 # 4 2 4 1 # 5 1 5 2 ```
50,549,935
I have a very large dataset in R with 1797 observations (rows) and 24 variables (columns) corresponding to a survey conducted through EPFL community. The respondents were asked at which frequency they perform 23 pro-environmental behaviours and they answered on a relative scale, leading to a score between 1 (for never) and 5 (for very often). [![enter image description here](https://i.stack.imgur.com/lq54a.png)](https://i.stack.imgur.com/lq54a.png) I would like to check for duplicated values inside each row in order to see if people answered randomly of seriously (e.g., someone having a lot of "3" values). Therefore, I want to retrieve these duplicates per row, do you have an idea of how I can do that? Thanks :)
2018/05/27
[ "https://Stackoverflow.com/questions/50549935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9853621/" ]
I guess the just want to count how often the questions were answered with the same value (no matter which question). This does it: ``` library(reshape2) data <- data.frame(ID = c(1, 2), Q1 = c(1, 4), Q2 = c(5, 2), Q3 = c(3, 2), Q4 = c(5, 2)) data # ID Q1 Q2 Q3 Q4 # 1 1 1 5 3 5 # 2 2 4 2 2 2 melted.data <- melt(data, "ID") # , measure.vars = "") melted.data melted.data$count <- 1 melted.data # "variable" contains the original column name now, "value" the cell content # ID variable value count # 1 1 Q1 1 1 # 2 2 Q1 4 1 # 3 1 Q2 5 1 # 4 2 Q2 2 1 # 5 1 Q3 3 1 # 6 2 Q3 2 1 # 7 1 Q4 5 1 # 8 2 Q4 2 1 # group by "ID" + "value" columns and calculate the sum for the column "count" # (I hate the "aggregate" syntax ;-) aggregate( count ~ ID + value, data = melted.data, sum) ID value count # 1 1 1 1 # 2 2 2 3 # 3 1 3 1 # 4 2 4 1 # 5 1 5 2 ```
Using DJV's sample data, we can find the mode for each row, then compute the ratio of use of this value : ``` modes <- as.numeric(apply(df[-1],1,function(x) names(sort(-table(x)))[1])) ratios <- rowSums(df[-1]==modes)/(ncol(df)-1) # or df$ratios <-... to store it in a new col # [1] 0.4 0.4 0.4 0.5 0.4 ```
50,549,935
I have a very large dataset in R with 1797 observations (rows) and 24 variables (columns) corresponding to a survey conducted through EPFL community. The respondents were asked at which frequency they perform 23 pro-environmental behaviours and they answered on a relative scale, leading to a score between 1 (for never) and 5 (for very often). [![enter image description here](https://i.stack.imgur.com/lq54a.png)](https://i.stack.imgur.com/lq54a.png) I would like to check for duplicated values inside each row in order to see if people answered randomly of seriously (e.g., someone having a lot of "3" values). Therefore, I want to retrieve these duplicates per row, do you have an idea of how I can do that? Thanks :)
2018/05/27
[ "https://Stackoverflow.com/questions/50549935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9853621/" ]
You can use the `tidyverse` approach. Sample data: ``` set.seed(123) df <- data.frame(id = c(1:5), q1 = sample(1:5, 5, replace = TRUE), q2 = sample(1:5, 5, replace = TRUE), q3 = sample(1:5, 5, replace = TRUE), q4 = sample(1:5, 5, replace = TRUE), q5 = sample(1:5, 5, replace = TRUE), q6 = sample(1:5, 5, replace = TRUE), q7 = sample(1:5, 5, replace = TRUE), q8 = sample(1:5, 5, replace = TRUE), q9 = sample(1:5, 5, replace = TRUE), q10 = sample(1:5, 5, replace = TRUE)) require(tidyverse) df %>% gather(question, value, -id) %>% group_by(id) %>% #Give you the count for each answer count(value) %>% ungroup() %>% #In addition, you can calculate the prop. of the same answer out of the 10 questions. mutate(prop = n / 10) ``` Output: ``` id value n prop 1 1 1 3 0.3 2 1 2 1 0.1 3 1 3 1 0.1 4 1 4 1 0.1 5 1 5 4 0.4 6 2 2 2 0.2 7 2 3 4 0.4 8 2 4 3 0.3 9 2 5 1 0.1 10 3 1 1 0.1 11 3 2 1 0.1 12 3 3 4 0.4 13 3 4 3 0.3 14 3 5 1 0.1 15 4 2 5 0.5 16 4 3 2 0.2 17 4 4 1 0.1 18 4 5 2 0.2 19 5 1 4 0.4 20 5 2 1 0.1 21 5 3 1 0.1 22 5 4 1 0.1 23 5 5 3 0.3 ```
Using DJV's sample data, we can find the mode for each row, then compute the ratio of use of this value : ``` modes <- as.numeric(apply(df[-1],1,function(x) names(sort(-table(x)))[1])) ratios <- rowSums(df[-1]==modes)/(ncol(df)-1) # or df$ratios <-... to store it in a new col # [1] 0.4 0.4 0.4 0.5 0.4 ```
50,549,935
I have a very large dataset in R with 1797 observations (rows) and 24 variables (columns) corresponding to a survey conducted through EPFL community. The respondents were asked at which frequency they perform 23 pro-environmental behaviours and they answered on a relative scale, leading to a score between 1 (for never) and 5 (for very often). [![enter image description here](https://i.stack.imgur.com/lq54a.png)](https://i.stack.imgur.com/lq54a.png) I would like to check for duplicated values inside each row in order to see if people answered randomly of seriously (e.g., someone having a lot of "3" values). Therefore, I want to retrieve these duplicates per row, do you have an idea of how I can do that? Thanks :)
2018/05/27
[ "https://Stackoverflow.com/questions/50549935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9853621/" ]
You can use the `tidyverse` approach. Sample data: ``` set.seed(123) df <- data.frame(id = c(1:5), q1 = sample(1:5, 5, replace = TRUE), q2 = sample(1:5, 5, replace = TRUE), q3 = sample(1:5, 5, replace = TRUE), q4 = sample(1:5, 5, replace = TRUE), q5 = sample(1:5, 5, replace = TRUE), q6 = sample(1:5, 5, replace = TRUE), q7 = sample(1:5, 5, replace = TRUE), q8 = sample(1:5, 5, replace = TRUE), q9 = sample(1:5, 5, replace = TRUE), q10 = sample(1:5, 5, replace = TRUE)) require(tidyverse) df %>% gather(question, value, -id) %>% group_by(id) %>% #Give you the count for each answer count(value) %>% ungroup() %>% #In addition, you can calculate the prop. of the same answer out of the 10 questions. mutate(prop = n / 10) ``` Output: ``` id value n prop 1 1 1 3 0.3 2 1 2 1 0.1 3 1 3 1 0.1 4 1 4 1 0.1 5 1 5 4 0.4 6 2 2 2 0.2 7 2 3 4 0.4 8 2 4 3 0.3 9 2 5 1 0.1 10 3 1 1 0.1 11 3 2 1 0.1 12 3 3 4 0.4 13 3 4 3 0.3 14 3 5 1 0.1 15 4 2 5 0.5 16 4 3 2 0.2 17 4 4 1 0.1 18 4 5 2 0.2 19 5 1 4 0.4 20 5 2 1 0.1 21 5 3 1 0.1 22 5 4 1 0.1 23 5 5 3 0.3 ```
Seems OP is looking for `maximum number of duplicate answer` per row. An option can to use `apply` and `table` functions of `base-R` as: **Option#1:** ``` # row-wise apply over columns starting with 'q' df$MaxDup <- apply(df[,startsWith(names(df),"q")], 1, function(x)sort(table(x), decreasing = TRUE)[1]) df # id q1 q2 q3 q4 q5 q6 q7 q8 q9 q10 MaxDup # 1 1 2 1 5 5 5 4 5 3 1 1 4 # 2 2 4 3 3 2 4 3 5 4 3 2 4 # 3 3 3 5 4 1 4 3 4 2 3 3 4 # 4 4 5 3 3 2 5 2 4 2 2 2 5 # 5 5 5 3 1 5 4 1 1 2 1 5 4 ``` **Option#2:** All the row-wise duplicates listed in a column separated by `;` ``` df$DupCount <- apply(df[,startsWith(names(df),"q")], 1, function(x){ dup <- sort(table(x), decreasing = TRUE) dup = dup[dup>1] paste0(paste(names(dup), dup, sep = "="), collapse = ";") }) df # id q1 q2 q3 q4 q5 q6 q7 q8 q9 q10 DupCount # 1 1 2 1 5 5 5 4 5 3 1 1 5=4;1=3 <- 5=4 times; 1=3 times # 2 2 4 3 3 2 4 3 5 4 3 2 3=4;4=3;2=2 <- 3=4 times; 4=3 times, 2=2 times # 3 3 3 5 4 1 4 3 4 2 3 3 3=4;4=3 # 4 4 5 3 3 2 5 2 4 2 2 2 2=5;3=2;5=2 # 5 5 5 3 1 5 4 1 1 2 1 5 1=4;5=3 ``` **Data:** Taken from @DJV anser ``` set.seed(123) df <- data.frame(id = c(1:5), q1 = sample(1:5, 5, replace = TRUE), q2 = sample(1:5, 5, replace = TRUE), q3 = sample(1:5, 5, replace = TRUE), q4 = sample(1:5, 5, replace = TRUE), q5 = sample(1:5, 5, replace = TRUE), q6 = sample(1:5, 5, replace = TRUE), q7 = sample(1:5, 5, replace = TRUE), q8 = sample(1:5, 5, replace = TRUE), q9 = sample(1:5, 5, replace = TRUE), q10 = sample(1:5, 5, replace = TRUE)) ```
50,549,935
I have a very large dataset in R with 1797 observations (rows) and 24 variables (columns) corresponding to a survey conducted through EPFL community. The respondents were asked at which frequency they perform 23 pro-environmental behaviours and they answered on a relative scale, leading to a score between 1 (for never) and 5 (for very often). [![enter image description here](https://i.stack.imgur.com/lq54a.png)](https://i.stack.imgur.com/lq54a.png) I would like to check for duplicated values inside each row in order to see if people answered randomly of seriously (e.g., someone having a lot of "3" values). Therefore, I want to retrieve these duplicates per row, do you have an idea of how I can do that? Thanks :)
2018/05/27
[ "https://Stackoverflow.com/questions/50549935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9853621/" ]
Seems OP is looking for `maximum number of duplicate answer` per row. An option can to use `apply` and `table` functions of `base-R` as: **Option#1:** ``` # row-wise apply over columns starting with 'q' df$MaxDup <- apply(df[,startsWith(names(df),"q")], 1, function(x)sort(table(x), decreasing = TRUE)[1]) df # id q1 q2 q3 q4 q5 q6 q7 q8 q9 q10 MaxDup # 1 1 2 1 5 5 5 4 5 3 1 1 4 # 2 2 4 3 3 2 4 3 5 4 3 2 4 # 3 3 3 5 4 1 4 3 4 2 3 3 4 # 4 4 5 3 3 2 5 2 4 2 2 2 5 # 5 5 5 3 1 5 4 1 1 2 1 5 4 ``` **Option#2:** All the row-wise duplicates listed in a column separated by `;` ``` df$DupCount <- apply(df[,startsWith(names(df),"q")], 1, function(x){ dup <- sort(table(x), decreasing = TRUE) dup = dup[dup>1] paste0(paste(names(dup), dup, sep = "="), collapse = ";") }) df # id q1 q2 q3 q4 q5 q6 q7 q8 q9 q10 DupCount # 1 1 2 1 5 5 5 4 5 3 1 1 5=4;1=3 <- 5=4 times; 1=3 times # 2 2 4 3 3 2 4 3 5 4 3 2 3=4;4=3;2=2 <- 3=4 times; 4=3 times, 2=2 times # 3 3 3 5 4 1 4 3 4 2 3 3 3=4;4=3 # 4 4 5 3 3 2 5 2 4 2 2 2 2=5;3=2;5=2 # 5 5 5 3 1 5 4 1 1 2 1 5 1=4;5=3 ``` **Data:** Taken from @DJV anser ``` set.seed(123) df <- data.frame(id = c(1:5), q1 = sample(1:5, 5, replace = TRUE), q2 = sample(1:5, 5, replace = TRUE), q3 = sample(1:5, 5, replace = TRUE), q4 = sample(1:5, 5, replace = TRUE), q5 = sample(1:5, 5, replace = TRUE), q6 = sample(1:5, 5, replace = TRUE), q7 = sample(1:5, 5, replace = TRUE), q8 = sample(1:5, 5, replace = TRUE), q9 = sample(1:5, 5, replace = TRUE), q10 = sample(1:5, 5, replace = TRUE)) ```
Using DJV's sample data, we can find the mode for each row, then compute the ratio of use of this value : ``` modes <- as.numeric(apply(df[-1],1,function(x) names(sort(-table(x)))[1])) ratios <- rowSums(df[-1]==modes)/(ncol(df)-1) # or df$ratios <-... to store it in a new col # [1] 0.4 0.4 0.4 0.5 0.4 ```
8,967,253
I am trying to write an Android app, and it's supposed to retrieve the content of a CDN URL, which are always URLEncoded. For the sake of example, I am using a youtube URL, because they are formatted the same way. ``` public static String getText(String url) throws Exception { URL website = new URL(url); URLConnection connection = website.openConnection(); BufferedReader in = new BufferedReader( new InputStreamReader( connection.getInputStream())); StringBuilder response = new StringBuilder(); String inputLine; while ((inputLine = in.readLine()) != null) response.append(inputLine); in.close(); return response.toString(); } /** * @param args the command line arguments */ public static void main(String[] args) { try { String page = getText("http://www.youtube.com/watch?v=QH2-TGUlwu4"); String[] temper = page.split("flashvars=\""); page = temper[1]; temper = page.split("\" allowscriptaccess=\"always\""); page = temper[0]; temper = page.split("url_encoded_fmt_stream_map="); page = temper[1]; temper = page.split("fallback_host"); page = temper[0]; page = page.replaceAll("url%3D", ""); ** page = URLDecoder.decode(page, "UTF-8"); ** page = page.replaceAll("hd720&", "hd720"); ** System.out.println(page); // TODO code application logic here } catch (Exception ex) { Logger.getLogger(app.class.getName()).log(Level.SEVERE, null, ex); } } ``` The code that is starred is (probably) where it is giving me trouble. The system.out.println outputs ``` http%3A%2F%2Fo-o.preferred.ord08s01.v3.lscache1.c.youtube.com%2Fvideoplayback%3Fsparams%3Did%252Cexpire%252Cip%252Cipbits%252Citag%252Csource%252Cratebypass%252Ccp%26fexp%3D909708%252C907322%252C908613%26itag%3D44%26ip%3D99.0.0.0%26signature%3D2889261E861AF0E724519652960C1BF31DA5BABD.A621580215B6416151470893E2D07BDE7AFF081E%26sver%3D3%26ratebypass%3Dyes%26source%3Dyoutube%26expire%3D1327316557%26key%3Dyt1%26ipbits%3D8%26cp%3DU0hRTFNMVF9KUUNOMV9LRlhGOlNaUzBvTG1tdEp2%26id%3D407dbe4c6525c2ee&quality=large& ``` I want that URL decoded in a way that I can wrap it in a method to download it. I have already tried the string.replaceAll() method. In short, It doesn't work Please help me regarding this.
2012/01/23
[ "https://Stackoverflow.com/questions/8967253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/965870/" ]
The string you have there is URL encoded. ``` String afterDecode = URLDecoder.decode(stringvalue, "UTF-8"); ```
using [URLDecoder](http://docs.oracle.com/javase/6/docs/api/java/net/URLDecoder.html)
9,403,476
I want "testhash" to be a hash, with an key of "hashelm", which contains an array or an array. I do this: ``` $testhash{hashelm}=( ["1A","1B"], ["2A","2B"] ); print Dumper(%testhash); ``` But I get this as output: ``` $VAR1 = 'hashelm'; $VAR2 = [ '2A', '2B' ]; ``` I would expect something more like: ``` $VAR1 = hashlelm => ( [ '1A', '1B' ]; [ '2A', '2B' ]; ) ``` What am I missing?? I've been using perl for **years** and this one really has me stumped!!!
2012/02/22
[ "https://Stackoverflow.com/questions/9403476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/221768/" ]
Hashes can only store scalar values; `(["1A", "1B"], ["2A", "2B"])` is a list value. When evaluated in this scalar context, you only get the last item in the list, namely `["2A", "2B"]`. You need to store a *reference* to a list value in the hash: ``` $testhash{hashelm} = [ ["1A","1B"], ["2A","2B"] ]; ``` Read more in the perl documentation on [list value constructors](http://perldoc.perl.org/perldata.html#List-value-constructors).
This will work: ``` $testhash{hashelm}=[ ["1A","1B"], ["2A","2B"] ]; ``` You have to use the square brackets for an anonymous array.
40,227,599
Table contains hidden template row and zero or more visible data rows. In end of table there is add button which shoud add new empty row to end of table. I tried ``` function addVariablesRow() { var t = document.getElementById("reportVariablesTable"); var rows = t.getElementsByTagName("tr"); var r = rows[rows.length - 1]; var x = rows[1].cloneNode(true); x.style.display = ""; r.parentNode.insertBefore(x, r); } ``` but it adds row **before** last row to table. How to add row after last row to table ? ASP.NET MVC4 application, bootstrap 3 modal, jquery, jquery-ui are used. html: ``` <div class="modal" id="reportVariables" tabindex="-1" role="dialog" aria-labelledby="reportVariablesLabel"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-body"> <table class="table table-condensed table-striped" id="reportVariablesTable"> <thead> <tr> <th>Name</th> <th>Value</th> <th>Calculate</th> </tr> </thead> <tbody> <!-- first row is hidden add template row --> <tr style='display:none'> <td> <input type="text" name="name"> </td> <td> <textarea name="valuetostore"></textarea> </td> <td> <select class="totaltype-select" id="totaltype" name="totaltype"> <option value=""></option> <option value="Sum">Summary</option> <option value="Lowest">Smallest</option> <option value="Highest">Biggers</option> </select> </td> </tr> <!-- other are visible data rows --> <tr> <td> <input type="text" name="name" value="variable1"> </td> <td> <textarea name="valuetostore">a-b</textarea> </td> <td> <select class="totaltype-select" id="totaltype" name="totaltype"> <option value=""></option> <option value="Sum">Summary</option> <option value="Lowest" selected>Smallest</option> <option value="Highest">Biggers</option> </select> </td> </tr> ... remaining rows </tbody> </table> <button onclick="addVariablesRow();">+</button> </div> </div> </div> </div> ``` Update I ned to clone template row which is first in body and make new row visible. I tried: ``` function addVariablesRow() { var $t = $("#reportVariablesTable"); var $row = $($t.find("tr")[1]); var r = $row.clone(); r[0].style.display = ""; r.appendTo($t); } ``` Is this best code ? Maybe it is bettet to find template row as first in body?
2016/10/24
[ "https://Stackoverflow.com/questions/40227599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742402/" ]
It can be done via jQuery like this, `$('#reportVariablesTable tr:last').after('<tr>...</tr><tr>...</tr>');` You can include anything within the after() method as long as it's valid HTML, including multiple rows as per the example above.
``` var t = document.getElementById("reportVariablesTable"); var row = document.createElement("tr") t.appendChild(row) ```
40,227,599
Table contains hidden template row and zero or more visible data rows. In end of table there is add button which shoud add new empty row to end of table. I tried ``` function addVariablesRow() { var t = document.getElementById("reportVariablesTable"); var rows = t.getElementsByTagName("tr"); var r = rows[rows.length - 1]; var x = rows[1].cloneNode(true); x.style.display = ""; r.parentNode.insertBefore(x, r); } ``` but it adds row **before** last row to table. How to add row after last row to table ? ASP.NET MVC4 application, bootstrap 3 modal, jquery, jquery-ui are used. html: ``` <div class="modal" id="reportVariables" tabindex="-1" role="dialog" aria-labelledby="reportVariablesLabel"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-body"> <table class="table table-condensed table-striped" id="reportVariablesTable"> <thead> <tr> <th>Name</th> <th>Value</th> <th>Calculate</th> </tr> </thead> <tbody> <!-- first row is hidden add template row --> <tr style='display:none'> <td> <input type="text" name="name"> </td> <td> <textarea name="valuetostore"></textarea> </td> <td> <select class="totaltype-select" id="totaltype" name="totaltype"> <option value=""></option> <option value="Sum">Summary</option> <option value="Lowest">Smallest</option> <option value="Highest">Biggers</option> </select> </td> </tr> <!-- other are visible data rows --> <tr> <td> <input type="text" name="name" value="variable1"> </td> <td> <textarea name="valuetostore">a-b</textarea> </td> <td> <select class="totaltype-select" id="totaltype" name="totaltype"> <option value=""></option> <option value="Sum">Summary</option> <option value="Lowest" selected>Smallest</option> <option value="Highest">Biggers</option> </select> </td> </tr> ... remaining rows </tbody> </table> <button onclick="addVariablesRow();">+</button> </div> </div> </div> </div> ``` Update I ned to clone template row which is first in body and make new row visible. I tried: ``` function addVariablesRow() { var $t = $("#reportVariablesTable"); var $row = $($t.find("tr")[1]); var r = $row.clone(); r[0].style.display = ""; r.appendTo($t); } ``` Is this best code ? Maybe it is bettet to find template row as first in body?
2016/10/24
[ "https://Stackoverflow.com/questions/40227599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742402/" ]
As you mentioned JQuery is an option, you could use something like this: ``` function addVariablesRow() { var $t = $("#reportVariablesTable"); var $row = $t.find("tbody tr").first(); var $newRow = $row.clone(); $newRow.appendTo($t).show(); } ```
``` var t = document.getElementById("reportVariablesTable"); var row = document.createElement("tr") t.appendChild(row) ```
40,227,599
Table contains hidden template row and zero or more visible data rows. In end of table there is add button which shoud add new empty row to end of table. I tried ``` function addVariablesRow() { var t = document.getElementById("reportVariablesTable"); var rows = t.getElementsByTagName("tr"); var r = rows[rows.length - 1]; var x = rows[1].cloneNode(true); x.style.display = ""; r.parentNode.insertBefore(x, r); } ``` but it adds row **before** last row to table. How to add row after last row to table ? ASP.NET MVC4 application, bootstrap 3 modal, jquery, jquery-ui are used. html: ``` <div class="modal" id="reportVariables" tabindex="-1" role="dialog" aria-labelledby="reportVariablesLabel"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-body"> <table class="table table-condensed table-striped" id="reportVariablesTable"> <thead> <tr> <th>Name</th> <th>Value</th> <th>Calculate</th> </tr> </thead> <tbody> <!-- first row is hidden add template row --> <tr style='display:none'> <td> <input type="text" name="name"> </td> <td> <textarea name="valuetostore"></textarea> </td> <td> <select class="totaltype-select" id="totaltype" name="totaltype"> <option value=""></option> <option value="Sum">Summary</option> <option value="Lowest">Smallest</option> <option value="Highest">Biggers</option> </select> </td> </tr> <!-- other are visible data rows --> <tr> <td> <input type="text" name="name" value="variable1"> </td> <td> <textarea name="valuetostore">a-b</textarea> </td> <td> <select class="totaltype-select" id="totaltype" name="totaltype"> <option value=""></option> <option value="Sum">Summary</option> <option value="Lowest" selected>Smallest</option> <option value="Highest">Biggers</option> </select> </td> </tr> ... remaining rows </tbody> </table> <button onclick="addVariablesRow();">+</button> </div> </div> </div> </div> ``` Update I ned to clone template row which is first in body and make new row visible. I tried: ``` function addVariablesRow() { var $t = $("#reportVariablesTable"); var $row = $($t.find("tr")[1]); var r = $row.clone(); r[0].style.display = ""; r.appendTo($t); } ``` Is this best code ? Maybe it is bettet to find template row as first in body?
2016/10/24
[ "https://Stackoverflow.com/questions/40227599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742402/" ]
``` var t = document.getElementById("reportVariablesTable"); var row = document.createElement("tr") t.appendChild(row) ```
``` $('#reportVariablesTable').find('tbody:last') .append($('#rep‌​ortVariablesTable') .‌​find('tbody:first').clone())‌​; ```
40,227,599
Table contains hidden template row and zero or more visible data rows. In end of table there is add button which shoud add new empty row to end of table. I tried ``` function addVariablesRow() { var t = document.getElementById("reportVariablesTable"); var rows = t.getElementsByTagName("tr"); var r = rows[rows.length - 1]; var x = rows[1].cloneNode(true); x.style.display = ""; r.parentNode.insertBefore(x, r); } ``` but it adds row **before** last row to table. How to add row after last row to table ? ASP.NET MVC4 application, bootstrap 3 modal, jquery, jquery-ui are used. html: ``` <div class="modal" id="reportVariables" tabindex="-1" role="dialog" aria-labelledby="reportVariablesLabel"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-body"> <table class="table table-condensed table-striped" id="reportVariablesTable"> <thead> <tr> <th>Name</th> <th>Value</th> <th>Calculate</th> </tr> </thead> <tbody> <!-- first row is hidden add template row --> <tr style='display:none'> <td> <input type="text" name="name"> </td> <td> <textarea name="valuetostore"></textarea> </td> <td> <select class="totaltype-select" id="totaltype" name="totaltype"> <option value=""></option> <option value="Sum">Summary</option> <option value="Lowest">Smallest</option> <option value="Highest">Biggers</option> </select> </td> </tr> <!-- other are visible data rows --> <tr> <td> <input type="text" name="name" value="variable1"> </td> <td> <textarea name="valuetostore">a-b</textarea> </td> <td> <select class="totaltype-select" id="totaltype" name="totaltype"> <option value=""></option> <option value="Sum">Summary</option> <option value="Lowest" selected>Smallest</option> <option value="Highest">Biggers</option> </select> </td> </tr> ... remaining rows </tbody> </table> <button onclick="addVariablesRow();">+</button> </div> </div> </div> </div> ``` Update I ned to clone template row which is first in body and make new row visible. I tried: ``` function addVariablesRow() { var $t = $("#reportVariablesTable"); var $row = $($t.find("tr")[1]); var r = $row.clone(); r[0].style.display = ""; r.appendTo($t); } ``` Is this best code ? Maybe it is bettet to find template row as first in body?
2016/10/24
[ "https://Stackoverflow.com/questions/40227599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742402/" ]
As you mentioned JQuery is an option, you could use something like this: ``` function addVariablesRow() { var $t = $("#reportVariablesTable"); var $row = $t.find("tbody tr").first(); var $newRow = $row.clone(); $newRow.appendTo($t).show(); } ```
It can be done via jQuery like this, `$('#reportVariablesTable tr:last').after('<tr>...</tr><tr>...</tr>');` You can include anything within the after() method as long as it's valid HTML, including multiple rows as per the example above.
40,227,599
Table contains hidden template row and zero or more visible data rows. In end of table there is add button which shoud add new empty row to end of table. I tried ``` function addVariablesRow() { var t = document.getElementById("reportVariablesTable"); var rows = t.getElementsByTagName("tr"); var r = rows[rows.length - 1]; var x = rows[1].cloneNode(true); x.style.display = ""; r.parentNode.insertBefore(x, r); } ``` but it adds row **before** last row to table. How to add row after last row to table ? ASP.NET MVC4 application, bootstrap 3 modal, jquery, jquery-ui are used. html: ``` <div class="modal" id="reportVariables" tabindex="-1" role="dialog" aria-labelledby="reportVariablesLabel"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-body"> <table class="table table-condensed table-striped" id="reportVariablesTable"> <thead> <tr> <th>Name</th> <th>Value</th> <th>Calculate</th> </tr> </thead> <tbody> <!-- first row is hidden add template row --> <tr style='display:none'> <td> <input type="text" name="name"> </td> <td> <textarea name="valuetostore"></textarea> </td> <td> <select class="totaltype-select" id="totaltype" name="totaltype"> <option value=""></option> <option value="Sum">Summary</option> <option value="Lowest">Smallest</option> <option value="Highest">Biggers</option> </select> </td> </tr> <!-- other are visible data rows --> <tr> <td> <input type="text" name="name" value="variable1"> </td> <td> <textarea name="valuetostore">a-b</textarea> </td> <td> <select class="totaltype-select" id="totaltype" name="totaltype"> <option value=""></option> <option value="Sum">Summary</option> <option value="Lowest" selected>Smallest</option> <option value="Highest">Biggers</option> </select> </td> </tr> ... remaining rows </tbody> </table> <button onclick="addVariablesRow();">+</button> </div> </div> </div> </div> ``` Update I ned to clone template row which is first in body and make new row visible. I tried: ``` function addVariablesRow() { var $t = $("#reportVariablesTable"); var $row = $($t.find("tr")[1]); var r = $row.clone(); r[0].style.display = ""; r.appendTo($t); } ``` Is this best code ? Maybe it is bettet to find template row as first in body?
2016/10/24
[ "https://Stackoverflow.com/questions/40227599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742402/" ]
It can be done via jQuery like this, `$('#reportVariablesTable tr:last').after('<tr>...</tr><tr>...</tr>');` You can include anything within the after() method as long as it's valid HTML, including multiple rows as per the example above.
``` $('#reportVariablesTable').find('tbody:last') .append($('#rep‌​ortVariablesTable') .‌​find('tbody:first').clone())‌​; ```
40,227,599
Table contains hidden template row and zero or more visible data rows. In end of table there is add button which shoud add new empty row to end of table. I tried ``` function addVariablesRow() { var t = document.getElementById("reportVariablesTable"); var rows = t.getElementsByTagName("tr"); var r = rows[rows.length - 1]; var x = rows[1].cloneNode(true); x.style.display = ""; r.parentNode.insertBefore(x, r); } ``` but it adds row **before** last row to table. How to add row after last row to table ? ASP.NET MVC4 application, bootstrap 3 modal, jquery, jquery-ui are used. html: ``` <div class="modal" id="reportVariables" tabindex="-1" role="dialog" aria-labelledby="reportVariablesLabel"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-body"> <table class="table table-condensed table-striped" id="reportVariablesTable"> <thead> <tr> <th>Name</th> <th>Value</th> <th>Calculate</th> </tr> </thead> <tbody> <!-- first row is hidden add template row --> <tr style='display:none'> <td> <input type="text" name="name"> </td> <td> <textarea name="valuetostore"></textarea> </td> <td> <select class="totaltype-select" id="totaltype" name="totaltype"> <option value=""></option> <option value="Sum">Summary</option> <option value="Lowest">Smallest</option> <option value="Highest">Biggers</option> </select> </td> </tr> <!-- other are visible data rows --> <tr> <td> <input type="text" name="name" value="variable1"> </td> <td> <textarea name="valuetostore">a-b</textarea> </td> <td> <select class="totaltype-select" id="totaltype" name="totaltype"> <option value=""></option> <option value="Sum">Summary</option> <option value="Lowest" selected>Smallest</option> <option value="Highest">Biggers</option> </select> </td> </tr> ... remaining rows </tbody> </table> <button onclick="addVariablesRow();">+</button> </div> </div> </div> </div> ``` Update I ned to clone template row which is first in body and make new row visible. I tried: ``` function addVariablesRow() { var $t = $("#reportVariablesTable"); var $row = $($t.find("tr")[1]); var r = $row.clone(); r[0].style.display = ""; r.appendTo($t); } ``` Is this best code ? Maybe it is bettet to find template row as first in body?
2016/10/24
[ "https://Stackoverflow.com/questions/40227599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742402/" ]
As you mentioned JQuery is an option, you could use something like this: ``` function addVariablesRow() { var $t = $("#reportVariablesTable"); var $row = $t.find("tbody tr").first(); var $newRow = $row.clone(); $newRow.appendTo($t).show(); } ```
``` $('#reportVariablesTable').find('tbody:last') .append($('#rep‌​ortVariablesTable') .‌​find('tbody:first').clone())‌​; ```
62,308,415
I have an old Macbook Pro 3,1 running ubuntu 20.04 and python 3.8. The mac CPU doesn't have support for avx (Advanced Vector Extensions) which is needed for tensorflow 2.2 so whilst tensorflow installs, it fails to run with the error: > > illegal instruction (core dumped) > > > I've surfed around and it seems that I need to use tensorflow 1.5 however there is no wheel for this for my configuration and I have the impression that I need to build one for myself. So here's my question... how do I even start to do that? Does anyone have a URL to Building-Stuff-For-Dummies or something similar please? (Any other suggestions also welcome) Thanks in advance for your help
2020/06/10
[ "https://Stackoverflow.com/questions/62308415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10208261/" ]
When calculating for the bias between the model and observed, it is important that you match the grids before conducting your analysis. In other words, pre-processing is always a must. So you'll either have to match the grid of the model to the observed or vice-versa before subtracting both files, else, your output won't make sense at all because of the difference. The easiest way to do this is to use special operators like CDO, NCO, NCL, etc. In your command line (though CDO is available in Python as well but with a different syntax needed than below) ``` ### Match the grids ### cdo remapbil,obs.nc model.nc model1.nc ### Subtract the files ### cdo sub model1.nc obs.nc bias.nc ``` You can then easily map the difference in Python. I prefer this method just because it's easier and lighter than pre-processing the data in Python. (sent from smartphone)
If you want to do this using Python (with CDO as a backend, which needs to be installed) you can use my package nctoolkit (<https://nctoolkit.readthedocs.io/en/latest/installing.html>). So, if your two files are named file1 and file2. You would first read them in as datasets. > > import nctoolkit as nc > > > data1 = nc.open\_data(file1) > > > data2 = nc.open\_data(file2) > > > You can then regrid the first dataset to have the same grid as the first. This is necessary so the cells match up. > > data1.regrid(data2) > > > You can just subtract the second dataset from the first. > > data1.sub(data2) > > > If you want to then convert this to an xarray object you can just do this: > > d1\_xr = data1.to\_xarray() > > > or if you wanted a pandas dataframe do this: > > d1\_df = data1.to\_dataframe() > > > There is also an autplotting method, using holoviews: > > df1\_df.plot() > > >
15,566,689
How to pass jquery value result into visualforce code for example: My jquery code is ``` $j('[id$=submit]').on("click", function(){ var output = [], $jselects = $j(".container .row .span6 #form-details select"), i; for (i=0; i < $jselects.length; i += 2) output.push($jselects.eq(i).find("option:selected").text() + ":" + $jselects.eq(i+1).find("option:selected").text()); }) ``` When i click this id, the output values are generated like b:b,s:s,a:a This values are stroed in to variable as `output` Here my visualforce code ``` <apex:commandButton id="submit" action="{!myMethod}" value="Submit" styleClass="btn btn-primary" reRender="block"> <apex:param name="myParam" value="output"/> </apex:commandButton> ``` When I press the id `submit`, get the output value from jquery and it will be set in the place of `output` in `<apex:param name="myParam" value="output"/>` this line. Here the output text are generated, but I need to know how send that value inside this `<apex>` code. Is it possible or not...? Appreciate for your answer...
2013/03/22
[ "https://Stackoverflow.com/questions/15566689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1598053/" ]
You have three options 1) Create actionfunction with parameter. Then call the actionfunction and pass the generated string as parameter, just like any other javascript function. 2) Use Javascript remoting. It lets you pass parameters along with method call. But it requires method to be static. 3)Use a hidden `<apex:hiddeninput>` field. Then using javascript set value of this input as your string. Then this will be passed to controller with any regular apex post events(`apex:commandButton or apex:commandLink`)
Here you have a good sample about how pass javascript values to apex methods: <http://blogs.developerforce.com/developer-relations/2009/10/passing-javascript-values-to-apex-controller.html> You should use `apex:actionFunction`
15,566,689
How to pass jquery value result into visualforce code for example: My jquery code is ``` $j('[id$=submit]').on("click", function(){ var output = [], $jselects = $j(".container .row .span6 #form-details select"), i; for (i=0; i < $jselects.length; i += 2) output.push($jselects.eq(i).find("option:selected").text() + ":" + $jselects.eq(i+1).find("option:selected").text()); }) ``` When i click this id, the output values are generated like b:b,s:s,a:a This values are stroed in to variable as `output` Here my visualforce code ``` <apex:commandButton id="submit" action="{!myMethod}" value="Submit" styleClass="btn btn-primary" reRender="block"> <apex:param name="myParam" value="output"/> </apex:commandButton> ``` When I press the id `submit`, get the output value from jquery and it will be set in the place of `output` in `<apex:param name="myParam" value="output"/>` this line. Here the output text are generated, but I need to know how send that value inside this `<apex>` code. Is it possible or not...? Appreciate for your answer...
2013/03/22
[ "https://Stackoverflow.com/questions/15566689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1598053/" ]
You have three options 1) Create actionfunction with parameter. Then call the actionfunction and pass the generated string as parameter, just like any other javascript function. 2) Use Javascript remoting. It lets you pass parameters along with method call. But it requires method to be static. 3)Use a hidden `<apex:hiddeninput>` field. Then using javascript set value of this input as your string. Then this will be passed to controller with any regular apex post events(`apex:commandButton or apex:commandLink`)
You can use RemoteAction like this: in javascript do this: ``` Visualforce.remoting.Manager.invokeAction( '{!$RemoteAction.yourController.yourfunction}',your_data, function(result, event){ //the result of your apex code } ); ``` in your apex do this: ``` @RemoteAction public static string yourfunction(String your_data) { // do your stuff return result; } ```
67,563,852
I'm reading this example on the Reader monad: <https://blog.ssanj.net/posts/2014-09-23-A-Simple-Reader-Monad-Example.html> that has this code: ``` import Control.Monad.Reader tom :: Reader String String tom = do env <- ask -- gives you the environment which in this case is a String return (env ++ " This is Tom.") ``` I understood what it does but I do not understand how `ask` can return anything. In Haskell, functions can act on many different types. `ask` is a function that has no input and returns the monad environment `m r`. I'm trying to understand what happens when I do ``` (runReader tom) "Who is this?" ``` Somehow, `runReader` will call `tom`, but how is it possible that the `ask` inside `tom` will be able to return an `env` with the text `Who is this?`?
2021/05/17
[ "https://Stackoverflow.com/questions/67563852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10116440/" ]
Every line of the `do` block in a Reader monad gets sent a copy of the environment in the background as if it had been passed in as an extra argument (and thanks to Haskell not having mutable data each one gets the same copy). The `ask` function takes its copy returns it as the value as well. It would help to replace the generic `m` in the type of `ask` with concrete type: `ask::Reader r r`. This reads `ask` is a monadic action whose value(the second r) is the same as the environment (the first r). In order for `ask` to be useful a `Reader r` context must be present (that is what the `do` block is there for). Within that context `r` is always sitting there waiting to be used. Think for a moment about how you might write this example without the Monad: ``` tom :: String -> String tom env = env ++ " This is Tom." jerry :: String -> String jerry env = env ++ " This is Tom." tomAndJerry :: String -> String tomAndJerry env = let t = tom env j = jerry env in (t ++"\n"++j) ``` Notice how `env` gets manually passed to each function? (This is by the way exactly what you get if you substitute the definition of `Reader r`, `ask` and `runReader` into the example.) The Reader monad simply wraps up the process of collecting and passing on the environment for us which is nice because it is a process we are prone to mess up (at least I am). Reader Monads are really handy when you have a configuration file you read once at start up and then reference throughout the rest of the program. In imperative languages you might make it a global const variable. In Haskell you could try to pass that value into every function that needed it, but it is easier and less bug prone to dump it into a Reader monad (and the result is exactly the same just without all the typing.) This comes with this side benefit of the type system tagging all the functions that depend on the config file so when the configuration format changes the compiler can point out all the places that might need to be updated.
I think you basically struggle with the definition of `Reader` and how it is used. So let's quickly build our own: ```hs newtype MyReader env a = MyReader (env -> a) ``` that's right a `Reader` can be just a *function* that takes the current environment and returns some `a` - here in a `newtype` wrapper so we can define some instances on it without much *extensions* `runReader` is really simple - it just applies the given environment to our wrapped function: ```hs runReader :: MyReader env a -> env -> a runReader (MyReader f) = f ``` that should probably answer most of your question - `runReader` will not call `tom` in your example - you provide it as an argument so *you* call the wrapped function with `tom` ;) --- But let's finish our Monad So let's start by making this a functor - GHC by now could derive it but I guess for understanding doing it by hand is better: ```hs instance Functor (MyReader env) where fmap f (MyReader rdr) = MyReader (f . rdr) ``` if you look closely you'll see that this is indeed just *function composition* - so the mapped reader will take an `env`, apply the wrapped function to it and after this `f` to this outcome. *Applicative* is next: ```hs instance Applicative (MyReader env) where pure a = MyReader (\_ -> a) (MyReader f_a_to_b) <*> (MyReader f_a) = MyReader (\env -> f_a_to_b env (f_a env)) ``` This should be easy enough - `pure a` is a reader that ignores the environment and returns the value given to `pure` no matter what. And you `<*>` two readers by providing the environment to both (I hope the naming helps - the first argument is a `MyReader env (a -> b)` the second a `MyReader env a` and the outcome should be `MyReader env b`) Now we can define the monad instance: ```hs instance Monad (MyReader env) where (MyReader f_a) >>= f_a_MyR_b = MyReader (\env -> let a = f_a env in runReader (f_a_MyR_b a) env) ``` So this (as the *applicative*) passes a environment provided to the resulting `MyReader` to both parts. Here using `runReader` to make it a bit simpler (didn't want to unpack yet again). --- Now for `ask` this one seems a bit special: it will bring the passed *environment* right *into* the monad. You could probably figure it out from it's type: `ask :: MyReader env env` **try!** but here it is: ```hs ask :: MyReader env env ask = MyReader (\env -> env) ``` So back to your question: > > How ask can return anything? > > > it does only when really when you `runReader` it: Take this simple example: ```hs tom :: Reader String String tom = do env <- ask -- gives you the environment which in this case is a String return (env ++ " This is Tom.") ``` it desugars to: ```hs tom = ask >>= (\a -> pure (a ++ " This is Tom.")) ``` and so if you do `runReader tom "Who is this"` and follow all the definitions above you end up with ```hs runReader tom "Who is this" = let a = (\env -> env) "Who is this" in (\env -> a ++ " This is Tom.") "Who is this" = let a = "Who is this" in a ++ " This is Tom." = "Who is this This is Tom". ``` --- don't define `Functor`/`Applicative` yourself --------------------------------------------- ```hs {-# LANGUAGE DeriveFunctor #-} import Control.Monad (ap) newtype MyReader env a = MyReader { runReader :: env -> a } deriving Functor instance Applicative (MyReader env) where pure = return (<*>) = ap instance Monad (MyReader env) where return a = MyReader (const a) (MyReader mr_a) >>= f_a_mr_b = MyReader (\env -> let a = mr_a env in runReader (f_a_mr_b a) env) ask :: MyReader env env ask = MyReader id ```
44,144,006
I am wanting to take a string and find `base64,` and get rid of that and everything prior to that example "asdfjljlkjaldf\_base64,234u0909230948098234082304802384023094" Notice "base64," ... I want ONLY everything after "base64," Desired: "234u0909230948098234082304802384023094" I was looking at this code "string test = "hello, base64, matching"; ``` string regexStrTest; regexStrTest = @"test\s\w+"; MatchCollection m1 = Regex.Matches(base64,, regexStrTest); //gets the second matched value string value = m1[1].Value; ``` but that is not quite what I want..
2017/05/23
[ "https://Stackoverflow.com/questions/44144006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You tried a regex that matches `test`, a whitespace, and 1+ word chars. The input string just did not match it. You may use ``` var results = Regex.Matches(s, @"base64,(\w+)") .Cast<Match>() .Select(m => m.Groups[1].Value) .ToList(); ``` See the [regex demo](http://regexstorm.net/tester?p=base64%2C%28%5Cw%2B%29&i=asdfjljlkjaldf_base64%2C234u0909230948098234082304802384023094). The pattern matches `base64,` substring and then *captures* into Group 1 one or more word chars with `(\w+)` pattern. The captured value is stored inside `match.Groups[1].Value`, just what you get with `.Select(m => m.Groups[1].Value)`.
Some of the other answers are good. Here is a very **simple regex** ``` string yourData = "asdfjljlkjaldf_base64,234u0909230948098234082304802384023094"; var newString = Regex.Replace(yourData, "^.*base64,", ""); ```
44,144,006
I am wanting to take a string and find `base64,` and get rid of that and everything prior to that example "asdfjljlkjaldf\_base64,234u0909230948098234082304802384023094" Notice "base64," ... I want ONLY everything after "base64," Desired: "234u0909230948098234082304802384023094" I was looking at this code "string test = "hello, base64, matching"; ``` string regexStrTest; regexStrTest = @"test\s\w+"; MatchCollection m1 = Regex.Matches(base64,, regexStrTest); //gets the second matched value string value = m1[1].Value; ``` but that is not quite what I want..
2017/05/23
[ "https://Stackoverflow.com/questions/44144006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Why *regular expressions*? `IndexOf` + `Substring` seems to be quite enough: ``` string source = "asdfjljlkjaldf_base64,234u0909230948098234082304802384023094"; string tag = "base64,"; string result = source.Substring(source.IndexOf(tag) + tag.Length); ```
Some of the other answers are good. Here is a very **simple regex** ``` string yourData = "asdfjljlkjaldf_base64,234u0909230948098234082304802384023094"; var newString = Regex.Replace(yourData, "^.*base64,", ""); ```
19,915,944
I am mainly a C++ programmer, but in my spare time I am attempting to come up to speed on C#. I have the following C++ function that I would like to convert- ``` #define COMPUTE_CRC32(cp,crc) (crc32lookup_table[((unsigned long)crc^(unsigned char)cp)&0xff]^(((unsigned long)crc>>8)&0x00FFFFFF)) unsigned long ComputeCRC32::Update(const void* ptrBytes, long numBytes) { const unsigned char* ptr_data = (const unsigned char*) ptrBytes; while ( --numBytes >= 0 ) { unsigned char data_byte = *ptr_data++ ; m_ulCRC = COMPUTE_CRC32( data_byte, m_ulCRC ); } return m_ulCRC; } ``` I know there are many ways to do this but would like to see what the best way was to do it. This is what I have created so far - ``` public uint Update(object ptrBytes, int numBytes) { byte * ptr_data = (byte) ptrBytes; while (--numBytes >= 0) { byte data_byte = *ptr_data++; m_ulCRC = (GlobalMembersComputeCRC32.crc32lookup_table[((uint)m_ulCRC ^ (byte)data_byte) & 0xff] ^ (((uint)m_ulCRC >> 8) & 0x00FFFFFF)); } return m_ulCRC; } ``` What would be the best way to convert the pointers? Is there a better way to rewrite this in C#?
2013/11/11
[ "https://Stackoverflow.com/questions/19915944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/124658/" ]
C# is a language that has pointers, but also has references (and [references are not necessarily addresses](http://blogs.msdn.com/b/ericlippert/archive/2009/02/17/references-are-not-addresses.aspx)). An array such as `byte[]` in C# is the usual way of representing something you might use pointers for in C++. To use pointers, you use [`unsafe`](http://msdn.microsoft.com/en-us/library/chfa2zb8%28v=vs.110%29.aspx). If you are thinking in C#, people tend to avoid `unsafe` as it is generally "unsafe"; the runtime instead enforces checks to avoid things like buffer overruns in arrays. Instead, the psuedo code for Crc32 might be: ``` public uint Crc32(byte[] data) { uint result; for (int i= 0; i < data.Length; i++) { byte data_byte = data[i]; result = doCrc(...stuff with data_byte...); } return result; } ``` Note that the `for` loop uses `data.Length` as its limit check (ref: [Eric Gunnerson: Efficiency of iteration over arrays](http://blogs.msdn.com/b/ericgu/archive/2004/04/18/115566.aspx)), as this can be optimised by the JIT against the array length. If you use a separate length parameter it can't be, so this is to be avoided (or combined with length, if the required iteration count might be less than the array length).
These pointers are not doing anything tricky. They're just array iterators. ``` public uint Update( byte[] ptrBytes, int numBytes ) { for( int i = 0; i < numBytes; i++ ) { byte data_byte = ptr_data[i]; m_ulCRC = ... } return m_ulCRC; } ```
11,900,828
I want to execute a python script from a bash script, and I want to store the output of the python script in a variable. In my python script, I print some stuff to screen and at the end I return a string with: ``` sys.exit(myString) ``` In my bash script, I did the following: ``` outputString=`python myPythonScript arg1 arg2 arg3 ` ``` But then when I check the value of `outputString` with `echo $outputString` I get everything that the Python script had printed to screen, but *not* the return value `myString`! How should I do this? EDIT: I need the string because that tells me where a file created by the Python script is located. I want to do something like: ``` fileLocation=`python myPythonScript1 arg1 arg2 arg1` python myPythonScript2 $fileLocation ```
2012/08/10
[ "https://Stackoverflow.com/questions/11900828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497180/" ]
`sys.exit(myString)` doesn't mean "return this string". If you pass a string to [`sys.exit`](http://docs.python.org/library/sys.html#sys.exit), `sys.exit` will consider that string to be an error message, and it will write that string to `stderr`. The closest concept to a return value for an entire program is its [exit status](https://en.wikipedia.org/wiki/Exit_status), which must be an integer. If you want to capture output written to stderr, [you can do something like](https://stackoverflow.com/questions/3130375/bash-script-store-stderr-in-variable) ``` python yourscript 2> return_file ``` You could do something like that in your bash script ``` output=$((your command here) 2> &1) ``` This is not guaranteed to capture only the value passed to `sys.exit`, though. Anything else written to stderr will also be captured, which might include logging output or stack traces. example: test.py ``` print "something" exit('ohoh') ``` t.sh ``` va=$(python test.py 2>&1) mkdir $va ``` `bash t.sh` *edit* Not sure why but in that case, I would write a main script and two other scripts... Mixing python and bash is pointless unless you really need to. ``` import script1 import script2 if __name__ == '__main__': filename = script1.run(sys.args) script2.run(filename) ```
`sys.exit()` should return an integer, not a string: ``` sys.exit(1) ``` The value `1` is in `$?`. ``` $ cat e.py import sys sys.exit(1) $ python e.py $ echo $? 1 ``` **Edit:** If you want to write to stderr, use [`sys.stderr`](http://docs.python.org/library/sys.html?highlight=sys.stderr#sys.stderr).
11,900,828
I want to execute a python script from a bash script, and I want to store the output of the python script in a variable. In my python script, I print some stuff to screen and at the end I return a string with: ``` sys.exit(myString) ``` In my bash script, I did the following: ``` outputString=`python myPythonScript arg1 arg2 arg3 ` ``` But then when I check the value of `outputString` with `echo $outputString` I get everything that the Python script had printed to screen, but *not* the return value `myString`! How should I do this? EDIT: I need the string because that tells me where a file created by the Python script is located. I want to do something like: ``` fileLocation=`python myPythonScript1 arg1 arg2 arg1` python myPythonScript2 $fileLocation ```
2012/08/10
[ "https://Stackoverflow.com/questions/11900828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497180/" ]
read it in the [docs](http://docs.python.org/library/sys.html). If you return anything but an `int` or `None` it will be printed to `stderr`. **To get just stderr while discarding stdout do:** ``` output=$(python foo.py 2>&1 >/dev/null) ```
Python documentation for sys.exit([arg])says: > > The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. > > > Moreover to retrieve the return value of the last executed program you could use the $? bash predefined variable. Anyway if you put a string as arg in sys.exit() it should be printed at the end of your program output in a separate line, so that you can retrieve it just with a little bit of parsing. As an example consider this: ``` outputString=`python myPythonScript arg1 arg2 arg3 | tail -0` ```
11,900,828
I want to execute a python script from a bash script, and I want to store the output of the python script in a variable. In my python script, I print some stuff to screen and at the end I return a string with: ``` sys.exit(myString) ``` In my bash script, I did the following: ``` outputString=`python myPythonScript arg1 arg2 arg3 ` ``` But then when I check the value of `outputString` with `echo $outputString` I get everything that the Python script had printed to screen, but *not* the return value `myString`! How should I do this? EDIT: I need the string because that tells me where a file created by the Python script is located. I want to do something like: ``` fileLocation=`python myPythonScript1 arg1 arg2 arg1` python myPythonScript2 $fileLocation ```
2012/08/10
[ "https://Stackoverflow.com/questions/11900828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497180/" ]
Do not use `sys.exit` like this. When called with a string argument, the exit code of your process will be 1, signaling an error condition. The string is printed to standard error to indicate what the error might be. `sys.exit` is not to be used to provide a "return value" for your script. Instead, you should simply print the "return value" to standard output using a `print` statement, then call `sys.exit(0)`, and capture the output in the shell.
Python documentation for sys.exit([arg])says: > > The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. > > > Moreover to retrieve the return value of the last executed program you could use the $? bash predefined variable. Anyway if you put a string as arg in sys.exit() it should be printed at the end of your program output in a separate line, so that you can retrieve it just with a little bit of parsing. As an example consider this: ``` outputString=`python myPythonScript arg1 arg2 arg3 | tail -0` ```
11,900,828
I want to execute a python script from a bash script, and I want to store the output of the python script in a variable. In my python script, I print some stuff to screen and at the end I return a string with: ``` sys.exit(myString) ``` In my bash script, I did the following: ``` outputString=`python myPythonScript arg1 arg2 arg3 ` ``` But then when I check the value of `outputString` with `echo $outputString` I get everything that the Python script had printed to screen, but *not* the return value `myString`! How should I do this? EDIT: I need the string because that tells me where a file created by the Python script is located. I want to do something like: ``` fileLocation=`python myPythonScript1 arg1 arg2 arg1` python myPythonScript2 $fileLocation ```
2012/08/10
[ "https://Stackoverflow.com/questions/11900828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497180/" ]
`sys.exit()` should return an integer, not a string: ``` sys.exit(1) ``` The value `1` is in `$?`. ``` $ cat e.py import sys sys.exit(1) $ python e.py $ echo $? 1 ``` **Edit:** If you want to write to stderr, use [`sys.stderr`](http://docs.python.org/library/sys.html?highlight=sys.stderr#sys.stderr).
In addition to what Tichodroma said, you might end up using this syntax: ``` outputString=$(python myPythonScript arg1 arg2 arg3) ```
11,900,828
I want to execute a python script from a bash script, and I want to store the output of the python script in a variable. In my python script, I print some stuff to screen and at the end I return a string with: ``` sys.exit(myString) ``` In my bash script, I did the following: ``` outputString=`python myPythonScript arg1 arg2 arg3 ` ``` But then when I check the value of `outputString` with `echo $outputString` I get everything that the Python script had printed to screen, but *not* the return value `myString`! How should I do this? EDIT: I need the string because that tells me where a file created by the Python script is located. I want to do something like: ``` fileLocation=`python myPythonScript1 arg1 arg2 arg1` python myPythonScript2 $fileLocation ```
2012/08/10
[ "https://Stackoverflow.com/questions/11900828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497180/" ]
In addition to what Tichodroma said, you might end up using this syntax: ``` outputString=$(python myPythonScript arg1 arg2 arg3) ```
Python documentation for sys.exit([arg])says: > > The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. > > > Moreover to retrieve the return value of the last executed program you could use the $? bash predefined variable. Anyway if you put a string as arg in sys.exit() it should be printed at the end of your program output in a separate line, so that you can retrieve it just with a little bit of parsing. As an example consider this: ``` outputString=`python myPythonScript arg1 arg2 arg3 | tail -0` ```
11,900,828
I want to execute a python script from a bash script, and I want to store the output of the python script in a variable. In my python script, I print some stuff to screen and at the end I return a string with: ``` sys.exit(myString) ``` In my bash script, I did the following: ``` outputString=`python myPythonScript arg1 arg2 arg3 ` ``` But then when I check the value of `outputString` with `echo $outputString` I get everything that the Python script had printed to screen, but *not* the return value `myString`! How should I do this? EDIT: I need the string because that tells me where a file created by the Python script is located. I want to do something like: ``` fileLocation=`python myPythonScript1 arg1 arg2 arg1` python myPythonScript2 $fileLocation ```
2012/08/10
[ "https://Stackoverflow.com/questions/11900828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497180/" ]
`sys.exit(myString)` doesn't mean "return this string". If you pass a string to [`sys.exit`](http://docs.python.org/library/sys.html#sys.exit), `sys.exit` will consider that string to be an error message, and it will write that string to `stderr`. The closest concept to a return value for an entire program is its [exit status](https://en.wikipedia.org/wiki/Exit_status), which must be an integer. If you want to capture output written to stderr, [you can do something like](https://stackoverflow.com/questions/3130375/bash-script-store-stderr-in-variable) ``` python yourscript 2> return_file ``` You could do something like that in your bash script ``` output=$((your command here) 2> &1) ``` This is not guaranteed to capture only the value passed to `sys.exit`, though. Anything else written to stderr will also be captured, which might include logging output or stack traces. example: test.py ``` print "something" exit('ohoh') ``` t.sh ``` va=$(python test.py 2>&1) mkdir $va ``` `bash t.sh` *edit* Not sure why but in that case, I would write a main script and two other scripts... Mixing python and bash is pointless unless you really need to. ``` import script1 import script2 if __name__ == '__main__': filename = script1.run(sys.args) script2.run(filename) ```
read it in the [docs](http://docs.python.org/library/sys.html). If you return anything but an `int` or `None` it will be printed to `stderr`. **To get just stderr while discarding stdout do:** ``` output=$(python foo.py 2>&1 >/dev/null) ```
11,900,828
I want to execute a python script from a bash script, and I want to store the output of the python script in a variable. In my python script, I print some stuff to screen and at the end I return a string with: ``` sys.exit(myString) ``` In my bash script, I did the following: ``` outputString=`python myPythonScript arg1 arg2 arg3 ` ``` But then when I check the value of `outputString` with `echo $outputString` I get everything that the Python script had printed to screen, but *not* the return value `myString`! How should I do this? EDIT: I need the string because that tells me where a file created by the Python script is located. I want to do something like: ``` fileLocation=`python myPythonScript1 arg1 arg2 arg1` python myPythonScript2 $fileLocation ```
2012/08/10
[ "https://Stackoverflow.com/questions/11900828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497180/" ]
`sys.exit(myString)` doesn't mean "return this string". If you pass a string to [`sys.exit`](http://docs.python.org/library/sys.html#sys.exit), `sys.exit` will consider that string to be an error message, and it will write that string to `stderr`. The closest concept to a return value for an entire program is its [exit status](https://en.wikipedia.org/wiki/Exit_status), which must be an integer. If you want to capture output written to stderr, [you can do something like](https://stackoverflow.com/questions/3130375/bash-script-store-stderr-in-variable) ``` python yourscript 2> return_file ``` You could do something like that in your bash script ``` output=$((your command here) 2> &1) ``` This is not guaranteed to capture only the value passed to `sys.exit`, though. Anything else written to stderr will also be captured, which might include logging output or stack traces. example: test.py ``` print "something" exit('ohoh') ``` t.sh ``` va=$(python test.py 2>&1) mkdir $va ``` `bash t.sh` *edit* Not sure why but in that case, I would write a main script and two other scripts... Mixing python and bash is pointless unless you really need to. ``` import script1 import script2 if __name__ == '__main__': filename = script1.run(sys.args) script2.run(filename) ```
Python documentation for sys.exit([arg])says: > > The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. > > > Moreover to retrieve the return value of the last executed program you could use the $? bash predefined variable. Anyway if you put a string as arg in sys.exit() it should be printed at the end of your program output in a separate line, so that you can retrieve it just with a little bit of parsing. As an example consider this: ``` outputString=`python myPythonScript arg1 arg2 arg3 | tail -0` ```
11,900,828
I want to execute a python script from a bash script, and I want to store the output of the python script in a variable. In my python script, I print some stuff to screen and at the end I return a string with: ``` sys.exit(myString) ``` In my bash script, I did the following: ``` outputString=`python myPythonScript arg1 arg2 arg3 ` ``` But then when I check the value of `outputString` with `echo $outputString` I get everything that the Python script had printed to screen, but *not* the return value `myString`! How should I do this? EDIT: I need the string because that tells me where a file created by the Python script is located. I want to do something like: ``` fileLocation=`python myPythonScript1 arg1 arg2 arg1` python myPythonScript2 $fileLocation ```
2012/08/10
[ "https://Stackoverflow.com/questions/11900828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497180/" ]
`sys.exit(myString)` doesn't mean "return this string". If you pass a string to [`sys.exit`](http://docs.python.org/library/sys.html#sys.exit), `sys.exit` will consider that string to be an error message, and it will write that string to `stderr`. The closest concept to a return value for an entire program is its [exit status](https://en.wikipedia.org/wiki/Exit_status), which must be an integer. If you want to capture output written to stderr, [you can do something like](https://stackoverflow.com/questions/3130375/bash-script-store-stderr-in-variable) ``` python yourscript 2> return_file ``` You could do something like that in your bash script ``` output=$((your command here) 2> &1) ``` This is not guaranteed to capture only the value passed to `sys.exit`, though. Anything else written to stderr will also be captured, which might include logging output or stack traces. example: test.py ``` print "something" exit('ohoh') ``` t.sh ``` va=$(python test.py 2>&1) mkdir $va ``` `bash t.sh` *edit* Not sure why but in that case, I would write a main script and two other scripts... Mixing python and bash is pointless unless you really need to. ``` import script1 import script2 if __name__ == '__main__': filename = script1.run(sys.args) script2.run(filename) ```
In addition to what Tichodroma said, you might end up using this syntax: ``` outputString=$(python myPythonScript arg1 arg2 arg3) ```
11,900,828
I want to execute a python script from a bash script, and I want to store the output of the python script in a variable. In my python script, I print some stuff to screen and at the end I return a string with: ``` sys.exit(myString) ``` In my bash script, I did the following: ``` outputString=`python myPythonScript arg1 arg2 arg3 ` ``` But then when I check the value of `outputString` with `echo $outputString` I get everything that the Python script had printed to screen, but *not* the return value `myString`! How should I do this? EDIT: I need the string because that tells me where a file created by the Python script is located. I want to do something like: ``` fileLocation=`python myPythonScript1 arg1 arg2 arg1` python myPythonScript2 $fileLocation ```
2012/08/10
[ "https://Stackoverflow.com/questions/11900828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497180/" ]
`sys.exit()` should return an integer, not a string: ``` sys.exit(1) ``` The value `1` is in `$?`. ``` $ cat e.py import sys sys.exit(1) $ python e.py $ echo $? 1 ``` **Edit:** If you want to write to stderr, use [`sys.stderr`](http://docs.python.org/library/sys.html?highlight=sys.stderr#sys.stderr).
read it in the [docs](http://docs.python.org/library/sys.html). If you return anything but an `int` or `None` it will be printed to `stderr`. **To get just stderr while discarding stdout do:** ``` output=$(python foo.py 2>&1 >/dev/null) ```
11,900,828
I want to execute a python script from a bash script, and I want to store the output of the python script in a variable. In my python script, I print some stuff to screen and at the end I return a string with: ``` sys.exit(myString) ``` In my bash script, I did the following: ``` outputString=`python myPythonScript arg1 arg2 arg3 ` ``` But then when I check the value of `outputString` with `echo $outputString` I get everything that the Python script had printed to screen, but *not* the return value `myString`! How should I do this? EDIT: I need the string because that tells me where a file created by the Python script is located. I want to do something like: ``` fileLocation=`python myPythonScript1 arg1 arg2 arg1` python myPythonScript2 $fileLocation ```
2012/08/10
[ "https://Stackoverflow.com/questions/11900828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497180/" ]
`sys.exit()` should return an integer, not a string: ``` sys.exit(1) ``` The value `1` is in `$?`. ``` $ cat e.py import sys sys.exit(1) $ python e.py $ echo $? 1 ``` **Edit:** If you want to write to stderr, use [`sys.stderr`](http://docs.python.org/library/sys.html?highlight=sys.stderr#sys.stderr).
Python documentation for sys.exit([arg])says: > > The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. > > > Moreover to retrieve the return value of the last executed program you could use the $? bash predefined variable. Anyway if you put a string as arg in sys.exit() it should be printed at the end of your program output in a separate line, so that you can retrieve it just with a little bit of parsing. As an example consider this: ``` outputString=`python myPythonScript arg1 arg2 arg3 | tail -0` ```
28,024,995
I need to get selected row data(id, name) with radio button. To be specific; ``` <tr data-ng-repeat=" list in listTypes"> <td>{{list.TaskId}}</td> <td>{{list.Comments}}</td> <td>{{list.RecordDate}}</td> <td>{{list.StartDate}}</td> <td>{{list.DueDate}}</td> <td>{{list.AssignTo}}</td> <td>{{list.AssignBy}}</td> <td><label class="switch"> <input type="radio" name="switch-radio1" checked="" value="0" ng-value="true" > <span></span> </label></td> </tr> ``` When selected radio button, I should get the datas(`taskId`, `comments`), which is selected row. Which function should I use it? (specially I need JS part) Thanks for any help.
2015/01/19
[ "https://Stackoverflow.com/questions/28024995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3665267/" ]
You can make use of `ng-model` for your checkbox which can be used as following: ``` <tr data-ng-repeat=" list in listTypes"> <td>{{list.TaskId}}</td> <td>{{list.Comments}}</td> <td>{{list.RecordDate}}</td> <td>{{list.StartDate}}</td> <td>{{list.DueDate}}</td> <td>{{list.AssignTo}}</td> <td>{{list.AssignBy}}</td> <td> <label class="switch"> <input type="radio" name="switch-radio1" ng-model="list.selected" ng-change="onTaskSelect(list)"> </label> </td> </tr> ``` Now your controller code will look something like this: ``` $scope.onTaskSelect = function(task) { // access your whole task object here. console.log(task.selected); // will be true when you select it or else false }; ```
First you need to assign a ng-model to your radio button and change your ng-value to something like the list.TaskId ``` <input type="radio" name="switch-radio1" ng-model="selectedItem" checked="" value="0" ng-value="list.TaskId" > ``` Now that you have the list.TaskId you can use [Array.prototype.filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) to look for the data in listTypes
28,024,995
I need to get selected row data(id, name) with radio button. To be specific; ``` <tr data-ng-repeat=" list in listTypes"> <td>{{list.TaskId}}</td> <td>{{list.Comments}}</td> <td>{{list.RecordDate}}</td> <td>{{list.StartDate}}</td> <td>{{list.DueDate}}</td> <td>{{list.AssignTo}}</td> <td>{{list.AssignBy}}</td> <td><label class="switch"> <input type="radio" name="switch-radio1" checked="" value="0" ng-value="true" > <span></span> </label></td> </tr> ``` When selected radio button, I should get the datas(`taskId`, `comments`), which is selected row. Which function should I use it? (specially I need JS part) Thanks for any help.
2015/01/19
[ "https://Stackoverflow.com/questions/28024995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3665267/" ]
You can make use of `ng-model` for your checkbox which can be used as following: ``` <tr data-ng-repeat=" list in listTypes"> <td>{{list.TaskId}}</td> <td>{{list.Comments}}</td> <td>{{list.RecordDate}}</td> <td>{{list.StartDate}}</td> <td>{{list.DueDate}}</td> <td>{{list.AssignTo}}</td> <td>{{list.AssignBy}}</td> <td> <label class="switch"> <input type="radio" name="switch-radio1" ng-model="list.selected" ng-change="onTaskSelect(list)"> </label> </td> </tr> ``` Now your controller code will look something like this: ``` $scope.onTaskSelect = function(task) { // access your whole task object here. console.log(task.selected); // will be true when you select it or else false }; ```
I found a way better than other. when we use "ng-model" don't need the name attribute and because of the use of "$parent" I think to access a single model to play the role of the name attribute and also binding data. Therefore, because of the following quotes, as each item has a scope, we must have a higher level to achieve the single model that we define. > > The ngRepeat directive instantiates a template once per item from a > collection. ***Each template instance gets its own scope***, where the > given loop variable is set to the current collection item, and $index > is set to the item index or key. > <https://code.angularjs.org/1.7.5/docs/api/ng/directive/ngRepeat> > > > $scope Properties : $parent Reference to the parent scope. > <https://code.angularjs.org/1.7.5/docs/api/ng/type/>$rootScope.Scope#$parent > > > in template HTML : ``` <table> <tr data-ng-repeat=" item in listTypes"> <td>{{list.TaskId}}</td> <td>{{list.Comments}}</td> <td>{{list.RecordDate}}</td> <td>{{list.StartDate}}</td> <td>{{list.DueDate}}</td> <td>{{list.AssignTo}}</td> <td>{{list.AssignBy}}</td> <td> <label class="switch"> <input type="radio" ng-model="$parent.rdoModel" ng-value="item" > </label> </td> </tr> </table> <button type="button" ng-click="Ok(rdoModel)">OK</button> ``` in Angularjs controller script : ``` $scope.rdoModel={}; $scope.Ok = function(item){ var data = item ; // access to all data of list item }; ```
116,372
I am trying to give the Search Center URL in User Profile->My Site Setting ->Preferred Search Center. Once I've given the url and clicking ok, if I again go to that location I am unable to see the new Search Center URL value. Can you any one help on this?
2014/09/25
[ "https://sharepoint.stackexchange.com/questions/116372", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/33214/" ]
There is currently a bug in SP2013, that by my understandings won't let you change the search center for my sites from the UI. The solution would be to do it with powershell instead. At the first row of the code, make sure that you change it to the name of your search service application. ``` $ssa = Get-SPEnterpriseSearchServiceApplication "Search Service Application" $ssa.SearchCenterUrl = "http://url/site/searchcentername/Pages/" $ssa.Update() ``` To clear things up a little bit: 1. Log into your server where central admin is running. 2. Open up and run PowerShell ISE as an administrator. 3. Type Add-pssnapin microsoft.sharepoint.powershell. Execute. ( This is to add the SharePoint API for powershell. ) 4. Type Get-spserviceapplication | ft typename . This will return the name of all your service applications. Look for name of your search application. 5. Copy the name of your search application, for example "Search Service Application" 6. Copy the code into the script panel. ( ctrl + r ) if it's missing. 7. Execute the script. After the change you would still see the wrong URL in the Preferred Search Center but if you try to search, you will see that the change was made. [Unable to change "Preferred search center" in My Site Settings](http://social.technet.microsoft.com/Forums/sharepoint/en-US/b88b0672-659b-471e-b489-cb6ef047fead/unable-to-change-preferred-search-center-in-my-site-settings?forum=sharepointgeneral)
If you have problem to change the URL after you have found that you have missed something like the /pages/ segment follow below solution resetting only **Sharepoint Search Host Controller** service from services.msc resolved the problem
116,372
I am trying to give the Search Center URL in User Profile->My Site Setting ->Preferred Search Center. Once I've given the url and clicking ok, if I again go to that location I am unable to see the new Search Center URL value. Can you any one help on this?
2014/09/25
[ "https://sharepoint.stackexchange.com/questions/116372", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/33214/" ]
There is currently a bug in SP2013, that by my understandings won't let you change the search center for my sites from the UI. The solution would be to do it with powershell instead. At the first row of the code, make sure that you change it to the name of your search service application. ``` $ssa = Get-SPEnterpriseSearchServiceApplication "Search Service Application" $ssa.SearchCenterUrl = "http://url/site/searchcentername/Pages/" $ssa.Update() ``` To clear things up a little bit: 1. Log into your server where central admin is running. 2. Open up and run PowerShell ISE as an administrator. 3. Type Add-pssnapin microsoft.sharepoint.powershell. Execute. ( This is to add the SharePoint API for powershell. ) 4. Type Get-spserviceapplication | ft typename . This will return the name of all your service applications. Look for name of your search application. 5. Copy the name of your search application, for example "Search Service Application" 6. Copy the code into the script panel. ( ctrl + r ) if it's missing. 7. Execute the script. After the change you would still see the wrong URL in the Preferred Search Center but if you try to search, you will see that the change was made. [Unable to change "Preferred search center" in My Site Settings](http://social.technet.microsoft.com/Forums/sharepoint/en-US/b88b0672-659b-471e-b489-cb6ef047fead/unable-to-change-preferred-search-center-in-my-site-settings?forum=sharepointgeneral)
Today I am setting up SP2019 and the bug still exist. To solve it, first go to your search service application. Update the Global Search Center. Then restart SharePoint Timer Service. Then update the to have the Preferred Search Center in MySite setup with the same URL. This time change is saved.
1,378,680
I'm wanting to update a record in my database which has two values, one is the ID, and one is the "description". The ID can never be changed, however I'm relying on the use of strongly-typed features to do it. So, I have the following: ``` Inherits="System.Web.Mvc.ViewPage<Business>" ``` Which is fine as it allows me to get everything back. The problem is when I use the following line: ``` <%= Html.TextBox("BusinessID", ViewData.Model.BusinessID, new { disabled = "disabled", style = "width:50px;", @class = "uppercase", maxlength = "4" })%> ``` With the `disabled = "disabled"` option it doesn't recognise the BusinessID and therefore doesn't pass it back to the controller which, in turn has problems binding the object up. Not that you'll need it, but here's the controller action: ``` [HttpPost] public ActionResult EditBusiness(Business business) { if (!ModelState.IsValid) return View(business); // update business here _contractsControlRepository.UpdateBusiness(business); return RedirectToAction("Businesses"); } ``` Any ideas why this is happening? I didn't realise form elements were completely hidden on postback when they're disabled. I don't want the users editing that particular field. I've also tried `Html.DisplayFor(b=>b.BusinessID)` without any luck.
2009/09/04
[ "https://Stackoverflow.com/questions/1378680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39693/" ]
display the id like this ``` Html.Hidden("BusinessID", ViewData.Model.BusinessID) <%=Model.BussinessID %> ``` this way you will have the id for the binding in the hidden tag and you will display the value in the label or you can use anything else that you want yo can do like this also ``` <input type="text" value="<%=Model.BussinessID %>" contentEditable="false"> ``` and put the hidden somewhere in the form
instead of Html.Textbox you can use Html.Hidden("BusinessID", ViewData.Model.BusinessID)
1,378,680
I'm wanting to update a record in my database which has two values, one is the ID, and one is the "description". The ID can never be changed, however I'm relying on the use of strongly-typed features to do it. So, I have the following: ``` Inherits="System.Web.Mvc.ViewPage<Business>" ``` Which is fine as it allows me to get everything back. The problem is when I use the following line: ``` <%= Html.TextBox("BusinessID", ViewData.Model.BusinessID, new { disabled = "disabled", style = "width:50px;", @class = "uppercase", maxlength = "4" })%> ``` With the `disabled = "disabled"` option it doesn't recognise the BusinessID and therefore doesn't pass it back to the controller which, in turn has problems binding the object up. Not that you'll need it, but here's the controller action: ``` [HttpPost] public ActionResult EditBusiness(Business business) { if (!ModelState.IsValid) return View(business); // update business here _contractsControlRepository.UpdateBusiness(business); return RedirectToAction("Businesses"); } ``` Any ideas why this is happening? I didn't realise form elements were completely hidden on postback when they're disabled. I don't want the users editing that particular field. I've also tried `Html.DisplayFor(b=>b.BusinessID)` without any luck.
2009/09/04
[ "https://Stackoverflow.com/questions/1378680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39693/" ]
display the id like this ``` Html.Hidden("BusinessID", ViewData.Model.BusinessID) <%=Model.BussinessID %> ``` this way you will have the id for the binding in the hidden tag and you will display the value in the label or you can use anything else that you want yo can do like this also ``` <input type="text" value="<%=Model.BussinessID %>" contentEditable="false"> ``` and put the hidden somewhere in the form
Is there a particular reason you are displaying the id? if not then leave it out and on your controller simply use TryUpdateModel() instead. or is that not what your asking? **edit** ``` <%= Html.TextBox("name","value", null, new { style="readonly"}) %> ``` **Edit 2** You might think about doing a route like //site/controller/yourbusinessid then you can use the id as it's passed to your controller and you can then, in your view, simply use `<%= Model.BusinessId %>` as a string.
1,378,680
I'm wanting to update a record in my database which has two values, one is the ID, and one is the "description". The ID can never be changed, however I'm relying on the use of strongly-typed features to do it. So, I have the following: ``` Inherits="System.Web.Mvc.ViewPage<Business>" ``` Which is fine as it allows me to get everything back. The problem is when I use the following line: ``` <%= Html.TextBox("BusinessID", ViewData.Model.BusinessID, new { disabled = "disabled", style = "width:50px;", @class = "uppercase", maxlength = "4" })%> ``` With the `disabled = "disabled"` option it doesn't recognise the BusinessID and therefore doesn't pass it back to the controller which, in turn has problems binding the object up. Not that you'll need it, but here's the controller action: ``` [HttpPost] public ActionResult EditBusiness(Business business) { if (!ModelState.IsValid) return View(business); // update business here _contractsControlRepository.UpdateBusiness(business); return RedirectToAction("Businesses"); } ``` Any ideas why this is happening? I didn't realise form elements were completely hidden on postback when they're disabled. I don't want the users editing that particular field. I've also tried `Html.DisplayFor(b=>b.BusinessID)` without any luck.
2009/09/04
[ "https://Stackoverflow.com/questions/1378680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39693/" ]
display the id like this ``` Html.Hidden("BusinessID", ViewData.Model.BusinessID) <%=Model.BussinessID %> ``` this way you will have the id for the binding in the hidden tag and you will display the value in the label or you can use anything else that you want yo can do like this also ``` <input type="text" value="<%=Model.BussinessID %>" contentEditable="false"> ``` and put the hidden somewhere in the form
You always have the option of either "hard-coding" the html element, or writing your own html helper method to do it. ``` public static string DisabledTextBox(this HtmlHelper helper, string name, object value) { return String.Format(@"<input type="text" name="{0}" id="{0}" disabled="disabled" value="{1}" />", name, value); } ```
37,203,194
I wanna make ajax calls in symfony2. I already done with ajax with flat php and i have no idea how to set up in this symfony framework. ``` <html> <head> <script> function showBook(str) { if (str == "") { document.getElementById("txtHint").innerHTML = ""; return; } else { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("txtHint").innerHTML = xmlhttp.responseText; } }; xmlhttp.open("GET","getuser.php?q="+str,true); xmlhttp.send(); } } function showAuthor(str){ if (str == "") { document.getElementById("txtHint").innerHTML = ""; return; } else { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("txtHint").innerHTML = xmlhttp.responseText; } }; xmlhttp.open("GET","getAuthor.php?q="+str,true); xmlhttp.send(); } } </script> </head> <body> <form action=""> Book name: <input type="text" id="txt1" onkeyup="showBook(this.value)"> <br><br> Author name:<input type="text" id="txt1" onkeyup="showAuthor(this.value)"> </form> <br> <div id="txtHint"><b>book info will be listed here...</b></div> </body> </html> ``` Where should i pass this request?? to controller?? how to set routes?? is there any way to use flat php instead of controller??
2016/05/13
[ "https://Stackoverflow.com/questions/37203194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5308115/" ]
You would pass the request to a controller action exposed using a route: <http://symfony.com/doc/current/book/routing.html> Then in your html code, if you are using twig and including javascript in a script tag, you can do ``` xmlhttp.open("GET","{{ path("route_name", {"parameter_name":"parameter_value"}) }}"); ``` If you want to access the route in an attached .js file, you can use FOSJsRoutingBundle to generate the route url
If you are in a form, you can do something like : ``` $(document).submit(function () { var url = $('form').attr('action'); var data = $('form').serialize(); $.post(url, data, function (data) { window.location.href = data.redirect; }) .fail(function () { $('form').replaceWith(data.form); }); }); ``` You just need to send the correct url : ``` $(document).on('click', 'a', function () { var url = window.location.href; $.get(url, function (data) { $('.container').replaceWith(data); }); }); ``` It is also possible to use a routing generate, simply add: `"friendsofsymfony/jsrouting-bundle": "dev-master"` to your composer.json. AppKernel.php : `new FOS\JsRoutingBundle\FOSJsRoutingBundle(`) Then config it in your routing.yml : ``` fos_js_routing: resource: "@FOSJsRoutingBundle/Resources/config/routing/routing.xml" ``` And finally use "expose" arg in your routing : ``` @Route("/{table}/index", name="beta.index", options={"expose"=true}) ``` *I use annotation routing* In your JS : ``` var url = Routing.generate('beta.index', { 'table': 'foo' }); ``` Hope it'll help you :)
69,018,853
In R, how can you count the number of observations fulfilling a condition over a time range? Specifically, I want to count the number of different `id` by `country` over the last 8 months, but only if `id` occurs at least twice during these 8 months. Hence, for the count, it does not matter whether an `id` occurs 2x or 100x (doing this in 2 steps is maybe easier). `NA` exists both in `id` and `country`. Since this could otherwise be taken care off, accounting for this is not necessary but still helpful. My current best try is, but does not account for the restriction (ID must appear at least twice in the previous 8 months) and also I find its counting odd when looking at the `dates="2017-12-12"`, where `desired_unrestricted` should be equal to **4** according to my counting but the code gives *2*. ``` dt[, date := as.Date(date)][ , totalids := sapply(date, function(x) length(unique(id[between(date, x - lubridate::month(8), x)]))), by = country] ``` --- **Data** ``` library(data.table) library(lubridate) ID <- c("1","1","1","1","1","1","2","2","2","3","3",NA,"4") Date <- c("2017-01-01","2017-01-01", "2017-01-05", "2017-05-01", "2017-05-01","2018-05-02","2017-01-01", "2017-01-05", "2017-05-01", "2017-05-01","2017-05-01","2017-12-12","2017-12-12" ) Value <- c(2,4,3,5,2,5,8,17,17,3,7,5,3) Country <- c("UK","UK","US","US",NA,"US","UK","UK","US","US","US","US","US") Desired <- c(1,1,0,2,NA,0,1,2,2,2,2,1,1) Desired_unrestricted <- c(2,2,1,3,NA,1,2,2,3,3,3,4,4) dt <- data.frame(id=ID, date=Date, value=Value, country=Country, desired_output=Desired, desired_unrestricted=Desired_unrestricted) setDT(dt) ``` Thanks in advance.
2021/09/01
[ "https://Stackoverflow.com/questions/69018853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15496831/" ]
This `data.table`-only answer is motivated by a [comment](https://stackoverflow.com/questions/68958126/can-i-count-number-of-rows-within-certain-values/68958336#comment121872436_68958126), ```r dt[, date := as.Date(date)] # if not already `Date`-class dt[, date8 := do.call(c, lapply(dt$date, function(z) seq(z, length=2, by="-8 months")[2])) ][, results := dt[dt, on = .(country, date > date8, date <= date), length(Filter(function(z) z > 1, table(id))), by = .EACHI]$V1 ][, date8 := NULL ] # id date value country desired_output desired_unrestricted results # <char> <Date> <num> <char> <num> <num> <int> # 1: 1 2017-01-01 2 UK 1 2 1 # 2: 1 2017-01-01 4 UK 1 2 1 # 3: 1 2017-01-05 3 US 0 1 0 # 4: 1 2017-05-01 5 US 1 3 2 # 5: 1 2017-05-01 2 <NA> NA NA 0 # 6: 1 2018-05-02 5 US 0 1 0 # 7: 2 2017-01-01 8 UK 1 2 1 # 8: 2 2017-01-05 17 UK 2 2 2 # 9: 2 2017-05-01 17 US 1 3 2 # 10: 3 2017-05-01 3 US 2 3 2 # 11: 3 2017-05-01 7 US 2 3 2 # 12: <NA> 2017-12-12 5 US 2 4 1 # 13: 4 2017-12-12 3 US 2 4 1 ``` That's a lot to absorb. Quick walk-through: * "8 months ago": ```r seq(z, length=2, by="-8 months")[2] ``` `seq.Date` (inferred by calling `seq` with a `Date`-class first argument) starts at `z` (current `date` for each row) and produces a sequence of length 2 with 8 months between them. `seq` always starts at the first argument, so `length=1` won't work (it'll only return `z`); `length=2` guarantees that the second value in the returned vector will be the "8 months before `date`" that we need. * Date subtraction: ```r [, date8 := do.call(c, lapply(dt$date, function(z) seq(...)[2])) ] ``` A simple base-R method for subtracting 8 months is `seq(date, length=2, by="-8 months")[2]`. `seq.Date` requires its first argument to be length-1, so we need to `sapply` or `lapply` it; unfortunately, `sapply` drops the class, so we `lapply` it and then programmatically `c`ombine them with `do.call(c, ...)` (since `c(..)` creates a list-column, and `unlist` will de-class it). (Perhaps this part can be improved.) We need that in `dt` *first* since we do a non-equi (range-based) join based on this value. * Counting `id` with 2 or more visits: ```r length(Filter(function(z) z > 1, table(id))) ``` We produce a `table(id)`, which gives us the count of each `id` within the join-period. `Filter(fun, ...)` allows us to reduce those that have a count below 2, and we're left with a named-vector of `id`s that had 2 or more visits. Retrieving the `length` is what we need. * Self non-equi join: ```r dt[dt, on = .(country, date > date8, date <= date), ... ] ``` Relatively straight-forward. This is an open/closed ranging, it can be changed to both-closed if you prefer. * Self non-equi join but count `id`s by-row: `by=.EACHI`. * Retrieve the results of that and assign into the original `dt`: ```r [, results := dt[...]$V1 ] ``` Since the non-equi join included a value (`length(Filter(...))`) without a name, it's named `V1`, and all we want is that. (To be honest, I don't know exactly why assigning it more directly doesn't work ... but the counts are all wrong. Perhaps it's backwards by-row tallying.) * Cleanup: ```r [, date8 := NULL ] ``` (Nothing fancy here, just proper data-stewardship :-) There are some discrepancies in my counts versus your `desired_output`, I wonder if those are just typos in the OP; I think the math is right ...
Although this question is tagged with `data.table`, here is a `dplyr::rowwise` solution to the problem. Is this what you had in mind? The output looks valid to me: The number of `ìd`s in the last 8 months which have a count of at least greater than `2`. ```r library(dplyr) library(lubridate) dt <- dt %>% mutate(date = as.Date(date)) dt %>% group_by(country) %>% group_modify(~ .x %>% rowwise() %>% mutate(totalids = .x %>% filter(date <= .env$date, date >= .env$date %m-% months(8)) %>% pull(id) %>% table() %>% `[`(. >1) %>% length )) #> # A tibble: 13 x 7 #> # Groups: country [3] #> country id date value desired_output desired_unrestricted totalids #> <chr> <chr> <date> <dbl> <dbl> <dbl> <int> #> 1 UK 1 2017-01-01 2 1 2 1 #> 2 UK 1 2017-01-01 4 1 2 1 #> 3 UK 2 2017-01-01 8 1 2 1 #> 4 UK 2 2017-01-05 17 2 2 2 #> 5 US 1 2017-01-05 3 0 1 0 #> 6 US 1 2017-05-01 5 1 3 2 #> 7 US 1 2018-05-02 5 0 1 0 #> 8 US 2 2017-05-01 17 1 3 2 #> 9 US 3 2017-05-01 3 2 3 2 #> 10 US 3 2017-05-01 7 2 3 2 #> 11 US <NA> 2017-12-12 5 2 4 1 #> 12 US 4 2017-12-12 3 2 4 1 #> 13 <NA> 1 2017-05-01 2 NA NA 0 ``` Created on 2021-09-02 by the [reprex package](https://reprex.tidyverse.org) (v2.0.1)
69,018,853
In R, how can you count the number of observations fulfilling a condition over a time range? Specifically, I want to count the number of different `id` by `country` over the last 8 months, but only if `id` occurs at least twice during these 8 months. Hence, for the count, it does not matter whether an `id` occurs 2x or 100x (doing this in 2 steps is maybe easier). `NA` exists both in `id` and `country`. Since this could otherwise be taken care off, accounting for this is not necessary but still helpful. My current best try is, but does not account for the restriction (ID must appear at least twice in the previous 8 months) and also I find its counting odd when looking at the `dates="2017-12-12"`, where `desired_unrestricted` should be equal to **4** according to my counting but the code gives *2*. ``` dt[, date := as.Date(date)][ , totalids := sapply(date, function(x) length(unique(id[between(date, x - lubridate::month(8), x)]))), by = country] ``` --- **Data** ``` library(data.table) library(lubridate) ID <- c("1","1","1","1","1","1","2","2","2","3","3",NA,"4") Date <- c("2017-01-01","2017-01-01", "2017-01-05", "2017-05-01", "2017-05-01","2018-05-02","2017-01-01", "2017-01-05", "2017-05-01", "2017-05-01","2017-05-01","2017-12-12","2017-12-12" ) Value <- c(2,4,3,5,2,5,8,17,17,3,7,5,3) Country <- c("UK","UK","US","US",NA,"US","UK","UK","US","US","US","US","US") Desired <- c(1,1,0,2,NA,0,1,2,2,2,2,1,1) Desired_unrestricted <- c(2,2,1,3,NA,1,2,2,3,3,3,4,4) dt <- data.frame(id=ID, date=Date, value=Value, country=Country, desired_output=Desired, desired_unrestricted=Desired_unrestricted) setDT(dt) ``` Thanks in advance.
2021/09/01
[ "https://Stackoverflow.com/questions/69018853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15496831/" ]
This `data.table`-only answer is motivated by a [comment](https://stackoverflow.com/questions/68958126/can-i-count-number-of-rows-within-certain-values/68958336#comment121872436_68958126), ```r dt[, date := as.Date(date)] # if not already `Date`-class dt[, date8 := do.call(c, lapply(dt$date, function(z) seq(z, length=2, by="-8 months")[2])) ][, results := dt[dt, on = .(country, date > date8, date <= date), length(Filter(function(z) z > 1, table(id))), by = .EACHI]$V1 ][, date8 := NULL ] # id date value country desired_output desired_unrestricted results # <char> <Date> <num> <char> <num> <num> <int> # 1: 1 2017-01-01 2 UK 1 2 1 # 2: 1 2017-01-01 4 UK 1 2 1 # 3: 1 2017-01-05 3 US 0 1 0 # 4: 1 2017-05-01 5 US 1 3 2 # 5: 1 2017-05-01 2 <NA> NA NA 0 # 6: 1 2018-05-02 5 US 0 1 0 # 7: 2 2017-01-01 8 UK 1 2 1 # 8: 2 2017-01-05 17 UK 2 2 2 # 9: 2 2017-05-01 17 US 1 3 2 # 10: 3 2017-05-01 3 US 2 3 2 # 11: 3 2017-05-01 7 US 2 3 2 # 12: <NA> 2017-12-12 5 US 2 4 1 # 13: 4 2017-12-12 3 US 2 4 1 ``` That's a lot to absorb. Quick walk-through: * "8 months ago": ```r seq(z, length=2, by="-8 months")[2] ``` `seq.Date` (inferred by calling `seq` with a `Date`-class first argument) starts at `z` (current `date` for each row) and produces a sequence of length 2 with 8 months between them. `seq` always starts at the first argument, so `length=1` won't work (it'll only return `z`); `length=2` guarantees that the second value in the returned vector will be the "8 months before `date`" that we need. * Date subtraction: ```r [, date8 := do.call(c, lapply(dt$date, function(z) seq(...)[2])) ] ``` A simple base-R method for subtracting 8 months is `seq(date, length=2, by="-8 months")[2]`. `seq.Date` requires its first argument to be length-1, so we need to `sapply` or `lapply` it; unfortunately, `sapply` drops the class, so we `lapply` it and then programmatically `c`ombine them with `do.call(c, ...)` (since `c(..)` creates a list-column, and `unlist` will de-class it). (Perhaps this part can be improved.) We need that in `dt` *first* since we do a non-equi (range-based) join based on this value. * Counting `id` with 2 or more visits: ```r length(Filter(function(z) z > 1, table(id))) ``` We produce a `table(id)`, which gives us the count of each `id` within the join-period. `Filter(fun, ...)` allows us to reduce those that have a count below 2, and we're left with a named-vector of `id`s that had 2 or more visits. Retrieving the `length` is what we need. * Self non-equi join: ```r dt[dt, on = .(country, date > date8, date <= date), ... ] ``` Relatively straight-forward. This is an open/closed ranging, it can be changed to both-closed if you prefer. * Self non-equi join but count `id`s by-row: `by=.EACHI`. * Retrieve the results of that and assign into the original `dt`: ```r [, results := dt[...]$V1 ] ``` Since the non-equi join included a value (`length(Filter(...))`) without a name, it's named `V1`, and all we want is that. (To be honest, I don't know exactly why assigning it more directly doesn't work ... but the counts are all wrong. Perhaps it's backwards by-row tallying.) * Cleanup: ```r [, date8 := NULL ] ``` (Nothing fancy here, just proper data-stewardship :-) There are some discrepancies in my counts versus your `desired_output`, I wonder if those are just typos in the OP; I think the math is right ...
Here is another option: ``` setkey(dt, country, date, id) dt[, date := as.IDate(date)][, eightmthsago := as.IDate(sapply(as.IDate(date), function(x) seq(x, by="-8 months", length.out=2L)[2L]))] dt[, c("out", "out_unres") := dt[dt, on=.(country, date>=eightmthsago, date<=date), by=.EACHI, { v <- id[!is.na(id)] .(uniqueN(v[duplicated(v)]), uniqueN(v)) }][,1L:3L := NULL] ] dt ``` output (like r2evans, I am also getting different output from desired as there seems to be a miscount in the desired output): ``` id date value country desired_output desired_unrestricted eightmthsago out out_unres 1: 1 2017-05-01 2 <NA> NA NA 2016-09-01 0 1 2: 1 2017-01-01 2 UK 1 2 2016-05-01 1 2 3: 1 2017-01-01 4 UK 1 2 2016-05-01 1 2 4: 2 2017-01-01 8 UK 1 2 2016-05-01 1 2 5: 2 2017-01-05 17 UK 2 2 2016-05-05 2 2 6: 1 2017-01-05 3 US 0 1 2016-05-05 0 1 7: 1 2017-05-01 5 US 1 3 2016-09-01 2 3 8: 2 2017-05-01 17 US 1 3 2016-09-01 2 3 9: 3 2017-05-01 3 US 2 3 2016-09-01 2 3 10: 3 2017-05-01 7 US 2 3 2016-09-01 2 3 11: <NA> 2017-12-12 5 US 2 4 2017-04-12 1 4 12: 4 2017-12-12 3 US 2 4 2017-04-12 1 4 13: 1 2018-05-02 5 US 0 1 2017-09-02 0 2 ```
59,518,911
I am trying to **upload a photo taken through my phone's camera** (With Ionic 4 Native `Camera Plugin` through **DevApp**) and upload it to `Firebase Storage`. Now I am able to take the photo, but when I upload it, the console does not throw any errors and just does not do anything. In the end, the photo is not uploaded to the firebase storage. Here are my codes: .html: ``` <ion-button (click)="takePicture()"></ion-button> ``` .ts: ``` takePicture(){ const options: CameraOptions = { quality: 100, destinationType: this.camera.DestinationType.FILE_URI, encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE } this.camera.getPicture(options).then((imageData) => { var storage = firebase.storage().ref(); var photoRef = storage.child('Manager Images'); console.log(photoRef); <-- This reference is correct let base64Image = 'data:image/jpeg;base64,' + imageData; console.log(base64Image); <-- Returns "data:image/jpeg;base64,file:///storage/emulated/0/Android/data/io.ionic.devapp/cache/1577622281686.jpg" // Base64 formatted string var message = imageData; photoRef.putString(message , 'base64', { contentType: 'image/jpg' }).then((savedPicture) => { console.log(savedPicture.downloadURL); }); }, (err) => { // Handle error }); } ``` Am I doing something wrong with the .putString method? I referred to <https://firebase.google.com/docs/storage/web/upload-files> for the guidelines but I still can't get this to work. Please help!
2019/12/29
[ "https://Stackoverflow.com/questions/59518911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9278490/" ]
Change destination type to `this.camera.DestinationType.DATA_URL` to get base64 and then put it into firebase storage. ``` takePicture(){ const options: CameraOptions = { quality: 100, destinationType: this.camera.DestinationType.DATA_URL, ... ``` PS. be sure if `let base64Image = 'data:image/jpeg;base64,' + imageData;` is necessarily or if `imageData` already has coded type in base64 format.
Change this line and it should work. ``` var message = base64Image; ``` imageData is not 'base64' Or Upload as File ,Use the file as it is. ``` var file = imageData photoRef.put(file).then(snapshot => { console.log('Uploaded a blob or file!') }); ```
13,591,798
I've two tables: purchase and items. For every date in the Purchase table, I'd like to see the number of items purchased for every single items in the Items table. Below is the result set I would expect from my query. The issue is that if no items were purchased for a given day, there's no record of it in the Purchase table. The dates must be coming from the Purchase table (no continuous dates). ``` +-------------------------+----------+----------+ | PurchaseDate | ItemName | Quantity | +-------------------------+----------+----------+ | 2000-01-01 00:00:00.000 | A | 1 | | 2000-01-01 00:00:00.000 | B | 2 | | 2000-01-01 00:00:00.000 | C | 4 | | 2000-01-04 00:00:00.000 | A | 6 | | 2000-01-04 00:00:00.000 | B | 0 | <- This row doesn't exist in Purchase | 2000-01-04 00:00:00.000 | C | 0 | <- This row doesn't exist in Purchase | 2000-01-07 00:00:00.000 | A | 0 | <- This row doesn't exist in Purchase | 2000-01-07 00:00:00.000 | B | 0 | <- This row doesn't exist in Purchase | 2000-01-07 00:00:00.000 | C | 3 | +-------------------------+----------+----------+ ``` What kind a query would give me the result above with the data below? I am using SQL Server 2008 R2. ``` CREATE TABLE Purchase ( PurchaseDate DATETIME, ItemName NVARCHAR(200), Quantity INT ) CREATE TABLE Items ( Value NVARCHAR(200) ) INSERT INTO Items VALUES ('A') INSERT INTO Items VALUES ('B') INSERT INTO Items VALUES ('C') INSERT INTO Purchase VALUES ('2000-01-01', 'A', 1) INSERT INTO Purchase VALUES ('2000-01-01', 'B', 2) INSERT INTO Purchase VALUES ('2000-01-01', 'C', 4) INSERT INTO Purchase VALUES ('2000-01-04', 'A', 6) INSERT INTO Purchase VALUES ('2000-01-07', 'C', 3) ```
2012/11/27
[ "https://Stackoverflow.com/questions/13591798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42024/" ]
You can cross join a distinct set of dates from the Purchase table to get your list of dates. This will only return a date if at least one item was purchased on a particular date: ``` SELECT dt.PurchaseDate, i.Value as ItemName, SUM(ISNULL(Quantity,0)) as Quantity FROM Items i CROSS JOIN ( SELECT DISTINCT PurchaseDate FROM Purchase ) dt LEFT OUTER JOIN Purchase p ON i.Value = p.ItemName AND dt.PurchaseDate = p.PurchaseDate GROUP BY dt.PurchaseDate, i.Value ORDER BY dt.PurchaseDate, i.Value ```
Unless you have a table with all calendar dates, or use a cursor approach, you won't be able to populate dates where nothing was purchased.
13,591,798
I've two tables: purchase and items. For every date in the Purchase table, I'd like to see the number of items purchased for every single items in the Items table. Below is the result set I would expect from my query. The issue is that if no items were purchased for a given day, there's no record of it in the Purchase table. The dates must be coming from the Purchase table (no continuous dates). ``` +-------------------------+----------+----------+ | PurchaseDate | ItemName | Quantity | +-------------------------+----------+----------+ | 2000-01-01 00:00:00.000 | A | 1 | | 2000-01-01 00:00:00.000 | B | 2 | | 2000-01-01 00:00:00.000 | C | 4 | | 2000-01-04 00:00:00.000 | A | 6 | | 2000-01-04 00:00:00.000 | B | 0 | <- This row doesn't exist in Purchase | 2000-01-04 00:00:00.000 | C | 0 | <- This row doesn't exist in Purchase | 2000-01-07 00:00:00.000 | A | 0 | <- This row doesn't exist in Purchase | 2000-01-07 00:00:00.000 | B | 0 | <- This row doesn't exist in Purchase | 2000-01-07 00:00:00.000 | C | 3 | +-------------------------+----------+----------+ ``` What kind a query would give me the result above with the data below? I am using SQL Server 2008 R2. ``` CREATE TABLE Purchase ( PurchaseDate DATETIME, ItemName NVARCHAR(200), Quantity INT ) CREATE TABLE Items ( Value NVARCHAR(200) ) INSERT INTO Items VALUES ('A') INSERT INTO Items VALUES ('B') INSERT INTO Items VALUES ('C') INSERT INTO Purchase VALUES ('2000-01-01', 'A', 1) INSERT INTO Purchase VALUES ('2000-01-01', 'B', 2) INSERT INTO Purchase VALUES ('2000-01-01', 'C', 4) INSERT INTO Purchase VALUES ('2000-01-04', 'A', 6) INSERT INTO Purchase VALUES ('2000-01-07', 'C', 3) ```
2012/11/27
[ "https://Stackoverflow.com/questions/13591798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42024/" ]
You can cross join a distinct set of dates from the Purchase table to get your list of dates. This will only return a date if at least one item was purchased on a particular date: ``` SELECT dt.PurchaseDate, i.Value as ItemName, SUM(ISNULL(Quantity,0)) as Quantity FROM Items i CROSS JOIN ( SELECT DISTINCT PurchaseDate FROM Purchase ) dt LEFT OUTER JOIN Purchase p ON i.Value = p.ItemName AND dt.PurchaseDate = p.PurchaseDate GROUP BY dt.PurchaseDate, i.Value ORDER BY dt.PurchaseDate, i.Value ```
``` select p.purchasedate, i.value, sum(case when p.itemname = i.value then p.quantity else 0 end) from Purchase p cross join Items i group by p.purchasedate, i.value order by p.purchasedate, i.value ```
13,591,798
I've two tables: purchase and items. For every date in the Purchase table, I'd like to see the number of items purchased for every single items in the Items table. Below is the result set I would expect from my query. The issue is that if no items were purchased for a given day, there's no record of it in the Purchase table. The dates must be coming from the Purchase table (no continuous dates). ``` +-------------------------+----------+----------+ | PurchaseDate | ItemName | Quantity | +-------------------------+----------+----------+ | 2000-01-01 00:00:00.000 | A | 1 | | 2000-01-01 00:00:00.000 | B | 2 | | 2000-01-01 00:00:00.000 | C | 4 | | 2000-01-04 00:00:00.000 | A | 6 | | 2000-01-04 00:00:00.000 | B | 0 | <- This row doesn't exist in Purchase | 2000-01-04 00:00:00.000 | C | 0 | <- This row doesn't exist in Purchase | 2000-01-07 00:00:00.000 | A | 0 | <- This row doesn't exist in Purchase | 2000-01-07 00:00:00.000 | B | 0 | <- This row doesn't exist in Purchase | 2000-01-07 00:00:00.000 | C | 3 | +-------------------------+----------+----------+ ``` What kind a query would give me the result above with the data below? I am using SQL Server 2008 R2. ``` CREATE TABLE Purchase ( PurchaseDate DATETIME, ItemName NVARCHAR(200), Quantity INT ) CREATE TABLE Items ( Value NVARCHAR(200) ) INSERT INTO Items VALUES ('A') INSERT INTO Items VALUES ('B') INSERT INTO Items VALUES ('C') INSERT INTO Purchase VALUES ('2000-01-01', 'A', 1) INSERT INTO Purchase VALUES ('2000-01-01', 'B', 2) INSERT INTO Purchase VALUES ('2000-01-01', 'C', 4) INSERT INTO Purchase VALUES ('2000-01-04', 'A', 6) INSERT INTO Purchase VALUES ('2000-01-07', 'C', 3) ```
2012/11/27
[ "https://Stackoverflow.com/questions/13591798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42024/" ]
Unless you have a table with all calendar dates, or use a cursor approach, you won't be able to populate dates where nothing was purchased.
``` select p.purchasedate, i.value, sum(case when p.itemname = i.value then p.quantity else 0 end) from Purchase p cross join Items i group by p.purchasedate, i.value order by p.purchasedate, i.value ```
44,175,114
I have seen many other answers and tried but they arent helping. My Python code ``` #!/usr/bin/env python3 print("Content-Type: text/html") print() print (""" <TITLE>CGI script ! Python</TITLE> <H1>This is my first CGI script</H1> """) ``` Its location and permission ``` -rwxr-xr-x. 1 root root 161 May 24 02:42 mypython.py [root@server cgi-bin]# pwd /var/www/mysite.com/cgi-bin ``` Virtual-Host conf ``` [root@server cgi-bin]# cat /etc/httpd/sites-available/mysite.com.conf <VirtualHost *:80> ServerName www.mysite.com DocumentRoot /var/www/mysite.com/public_html ServerAlias mysite.com ScriptAlias /cgi-bin/ "/var/www/mysite.com/cgi-bin/" <Directory /var/www/mysite.com> Options Indexes FollowSymLinks Includes ExecCGI AddHandler cgi-script .cgi .py AllowOverride None Require all granted </Directory> ErrorLog /var/log/httpd/mysite.com/error.log CustomLog /var/log/httpd/mysite.com/requests.log combined </VirtualHost> [root@server cgi-bin]# ``` While trying to access , I am getting below error ``` [Wed May 24 02:42:53.958318 2017] [cgid:error] [pid 7943] [client 192.168.56.1:52390] End of script output before headers: mypython.py [Wed May 24 02:42:54.661338 2017] [cgid:error] [pid 7939] [client 192.168.56.1:52391] End of script output before headers: mypython.py [Wed May 24 02:42:59.383215 2017] [cgid:error] [pid 7940] [client 192.168.56.1:52392] End of script output before headers: mypython.py ``` Please let me know if more information required. Thank you.
2017/05/25
[ "https://Stackoverflow.com/questions/44175114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1293013/" ]
I suspect your problem might be the ``` print() ``` In Python 2.7.12 at least this prints **()** and not a blank line as you might expect Please post the exact output of the script as it is right now.
First of all I take it you web-server is running as root otherwise your execute file permission is wrong. Secondly if you run the file from the command line it outputs: ``` Content-Type: text/html <TITLE>CGI script ! Python</TITLE> <H1>This is my first CGI script</H1> ``` Note there are two empty lines not one, this is bad as there should be only one see <https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html> But if you change your code slightly to remove the other empty line it works. ``` print ("""<TITLE>CGI script ! Python</TITLE> <H1>This is my first CGI script</H1> """) ```
54,665,992
I came before this very weird error: > > Msg 7999, Level 16, State 9, Line 12 > Could not find any index named 'IX\_MyIndex' for table 'dbo.MyTable'. > > > When running the script to create it!! ``` CREATE NONCLUSTERED INDEX [IX_MyIndex] ON [dbo].[MyTable] ( [Field1] ,[Field2] ) INCLUDE ( Fields3 ,Fields4 ,Fields5 ) WITH ( MAXDOP = 4 ,DATA_COMPRESSION = PAGE ,DROP_EXISTING = ON ) ``` What am I missing?
2019/02/13
[ "https://Stackoverflow.com/questions/54665992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4295234/" ]
Remove the last line and execute it. ``` CREATE NONCLUSTERED INDEX [IX_MyIndex] ON [dbo].[MyTable] ([Field1],[Field2]) INCLUDE (Fields3, Fields4, Fields5) ``` It is trying to search index with name - `IX_MyIndex` which is not available. But after creating an index of name `IX_MyIndex` you can run the same query.
With the help of Suraj's answer I found that the problem was the option: ``` DROP_EXISTING=ON ``` It does not work as I suspected (drop the index IF exists), instead it tries to find it and drop it! Removing it did the trick!
53,641,374
I have [a custom module for Ansible written in Python](https://github.com/naftulikay/ansible-role-degoss/pull/36) that I maintain, and I need to be able to pass in all detected Ansible facts as a dictionary into this module. Currently, I'm attempting to do this like so: ``` - name: run tests degoss: # ... facts: "{{ ansible_facts }}" ``` My module's argument spec looks like this: ``` AnsibleModule(argument_spec=dict( # ... facts=dict(required=False, default={}), ), ...) ``` My module documentation also specifies this: ``` DOCUMENTATION=""" # ... options: facts: required: false default: empty dictionary description: A dictionary of Ansible facts. """ ``` However, as I do input sanitization and validation, I receive a `str` instead of a dictionary: ``` if not isinstance(self.facts, dict): self.fail("The 'facts' parameter to this module must be a dictionary, not a {}".format(type(self.facts))) ``` This is thrown at runtime: ``` The 'facts' parameter to this module must be a dictionary, not a <type 'str'> ``` Is there a specific syntax I need to use to pass a value as a dictionary, or do I need to treat dictionary variables as JSON and attempt to deserialize them?
2018/12/05
[ "https://Stackoverflow.com/questions/53641374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/128967/" ]
As described [here](https://docs.ansible.com/ansible/latest/dev_guide/developing_program_flow_modules.html#type), you can specify what type ansible can expect. ``` AnsibleModule(argument_spec=dict( # ... facts=dict(required=False, default={}, type=dict), ), ...) ``` Then 'facts' will be a dictionary
This works: 1. Pass ansible\_facts piping it to `to_json` filter in your play. ``` - name: run tests degoss: # ... facts: "{{ ansible_facts | to_json }}" ``` 2. In your python module decode the json using **either** `json.loads` or `ast.literal_eval` ``` import json import ast ... facts = json.loads(module.params.get('facts')) facts = ast.literal_eval(module.params.get('facts')) ... ```
46,980
If 1,000 Aliens **secretly** invaded earth would they take over the earth and start anew? These Aliens crash landed on our planet long ago, so their technology for the most part is destroyed. The only thing they manage to retained are advanced weapons that can destroy Nuclear Weapons without nuclear fallout occurring. These Aliens have the special and unique ability to change/manipulate their cellular structure. (They have complete control over their anatomies and bodies of themselves, including skin, nails, fat, muscles, blood, metabolism, nerves, etc., allowing them to freely alter and manipulate them. For example they can grow additional appendages and body-parts, remove them or otherwise manipulate them, in visible, chemical and cellular/sub-cellular levels.) Each one are in the main Countries there are 10 stationed per country these countries are: Russia, Italy, Brazil, India, France, United Kingdom, Germany, Japan, China, and The United States of America. The other 900 are located in other countries but are meant to stay incognito until they are given the signal. These Aliens goal are to start anew. To become the apex species of Earth and rule. Their government for now is kind of like a council. The ten in each country share a collective hive mind. **Only these certain ten in each country have the hive mind.** So the ten in France share a hive mind with each other, the ten in china share a hivemind with each other, etc etc. They can also reproduce with humans and other Aliens. They take on average 5 months before the child is born and they generally have more than one kid per pregnancy. They can become female or male depending on how they changed their bodies. Their shape-shifting abilities are detailed enough to bypass highly sensitive eye-scans and voice-scans. They are basically immortal as they can stay young forever. They can be killed only in a few ways, destroying their brain 100% completely, though few modify themselves to avoid suffering that fate. Completely destroying their bodies is another way. Though keeping them locked up is a option but it is not easy. How would they go about taking over? EDIT: While pregnant they can not use their shape changing abilties at all. They are basically human with a weak healing factor while pregnant
2016/07/12
[ "https://worldbuilding.stackexchange.com/questions/46980", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/22813/" ]
You have a pretty interesting premise, depending on how you choose to use it. If you decide to go with it as a straight-up conspiracy takeover, they'll obviously be successful without an issue. What I see potential for is a situation in which they *indirectly* destroy humanity. Not through direct, successful plotting, but rather through a failed attempt, followed by skillful evasion. I could see the aliens attempting a coup, but not having properly planned for it. Following this, word gets out worldwide, and humans start organizing witch hunts for the *indistinguishable* aliens. Over time, the hysteria and paranoia of the unseen invader applying constant pressure to the collective human psyche eventually breaks something. Local militia tearing apart neighborhoods, marshal law, strict curfews, the curtailing of personal freedoms.Eventually the aliens will have taken over earth not through action, but rather inaction. Here we see the aliens not so much as an external antagonist, but rather as a catalyst for humanity's own demise. For an even more poignant message, the aliens could have accidentally revealed themselves without any harmful intentions. I find great sci-fi does is best to teach us about ourselves in a somewhat removed setting, so that we may be an outside observer to our own condition. > > *It is science fiction that holds a mirror to this age > > - Brian Aldiss* > > >
This is your story and they will take over if you want them to take over. It feels like the most important variable is kind of random : do they get found out by the humans ? If not, they have no reason not to be able to take over, they are basically a better version of us. As MolbOrg said, just procreate and multiply. However, if they do get found out, things get interesting althought once again depends on your story. As Aify said, humans are pretty good at killing off other species, and we'd be very keen on killing them if they are trying to take over. On both sides, strategies can be thought up to beet the other species but considering we are over 7 billion with access to a huge amount of technology and thousands of years of experience killing each other, I'm guessing humans would win. The end result of a fight against humans and these aliens would obviously depend on how soon humans find out that a bunch of aliens are living among us and are trying to take over.
46,980
If 1,000 Aliens **secretly** invaded earth would they take over the earth and start anew? These Aliens crash landed on our planet long ago, so their technology for the most part is destroyed. The only thing they manage to retained are advanced weapons that can destroy Nuclear Weapons without nuclear fallout occurring. These Aliens have the special and unique ability to change/manipulate their cellular structure. (They have complete control over their anatomies and bodies of themselves, including skin, nails, fat, muscles, blood, metabolism, nerves, etc., allowing them to freely alter and manipulate them. For example they can grow additional appendages and body-parts, remove them or otherwise manipulate them, in visible, chemical and cellular/sub-cellular levels.) Each one are in the main Countries there are 10 stationed per country these countries are: Russia, Italy, Brazil, India, France, United Kingdom, Germany, Japan, China, and The United States of America. The other 900 are located in other countries but are meant to stay incognito until they are given the signal. These Aliens goal are to start anew. To become the apex species of Earth and rule. Their government for now is kind of like a council. The ten in each country share a collective hive mind. **Only these certain ten in each country have the hive mind.** So the ten in France share a hive mind with each other, the ten in china share a hivemind with each other, etc etc. They can also reproduce with humans and other Aliens. They take on average 5 months before the child is born and they generally have more than one kid per pregnancy. They can become female or male depending on how they changed their bodies. Their shape-shifting abilities are detailed enough to bypass highly sensitive eye-scans and voice-scans. They are basically immortal as they can stay young forever. They can be killed only in a few ways, destroying their brain 100% completely, though few modify themselves to avoid suffering that fate. Completely destroying their bodies is another way. Though keeping them locked up is a option but it is not easy. How would they go about taking over? EDIT: While pregnant they can not use their shape changing abilties at all. They are basically human with a weak healing factor while pregnant
2016/07/12
[ "https://worldbuilding.stackexchange.com/questions/46980", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/22813/" ]
Based on the details of your *current* question (which sounds as though it has changed a lot from the original version), it seems to me that they **would likely succeed** in taking over. * They are effectively immortal, *and* can reproduce as well, which means that time is very much on their side. In addition to the sheer capacity for population growth, they can build power bases, accumulate wealth and knowledge and skill at unheard of levels. * Even with its range limits, the hive mind capabilities are a powerful advantage. Anything that anyone learns (in each country) is known to all of them. In a true hive mind that means not just information, but skills. How powerful the hive mind is depends on how quickly and fully the aliens can access it, and whether new descendants will be plugged into the country-hives. * They can blend in, and evade, better than anyone. Someone gets suspicious? Move and change your body to be a completely different person. * Speaking of which, it sounds like they could replace key people of power. Military commanders, businessmen, politicians, presidents. We know that they can physically take their exact form, perfectly, down to fingerprints and DNA. That means identical voice is possible as well. Manner of speech and psychological traits might be more difficult for them to reproduce. * They are motivated. Unless there is strife within their society, they are a fairly large group [even initially] which is unified towards a particular goal. A few comments on parts of your scenario that may complicate your storyline; * The anti-nuke tech seems pretty useless. Nukes are never a threat to them, since they're fully blended into human society. Perhaps they could use it at some point to cripple a country, by taking out all of its nuclear power plants. * The ability to reproduce with humans seems complicated. Would hybrid progeny still have the full set of capabilities of the alien race? If no, what's different? Certainly these hybrids would be conflicted individuals, who feel somewhere between super-human, and sub-alien. Likewise the 5 month gestation period would be highly suspicious to the human parent [if they're around], and any decent OBGYN. You could use some of that to add interest to your story. For example, the biggest threat to the alien race might just be their half-alien descendents.
Yes. The shape changing ability alone is enough to allow them to live along side humans without discovery. Having children with humans may not help them since they are the ones carrying the child. If a human female can carry the alien baby then they think the baby is premature at 5 months. (you may have to expand on that part since the baby probably doesn't have a clue how to control its form and would be born looking like the original alien until it did.) Another thing you have to tell us is at what age do they become sexually mature. If they are going for maximum growth rate then they would all be female in form so they can get pregnant. If they get pregnant twice a year they will hit 5000 new aliens in a year. I'm going to assume that they want to blend in so they can't just pop out 5000 every year without drawing attention so they stick to 5000 let them mature and then have them all become female and deal with breeding while the original 1000 worry about hiding and organization. If it takes 10 years to reach maturity and they wait the 10 years each time, just to keep the math simple, then the grown rate would be: 1000 year 1. 5000 year 2. 17,000 year 12. 81,000 year 22. 401,000 year 32. 2,001,000 year 42. 10,001,000 year 52... In 50 years they hit 10 million. And that number is assuming they wait 10 years before having a burst of children. It would most likely be much faster and the kids spread out a bit more than twice in a year but the effect would be the same. In 10 years they would have enough to really take control of an area so they could grow undisturbed. In 20 years they would have communities all over. Before all of that once the initial group was done with the first group of kids they would place themselves in charge of the nuclear powers of the world and not even need their anti nuke weapon. Others have brought up what if they are found out and I think it is quite possible for them to be found out during child birth if the baby doesn't come out human. Also what happens when they die? Some are going to get into car accidents and have autopsies performed on them. Do they turn back? Are the organs obviously not human? Assuming they do look human are they human at a cellular level? Will a blood test show they aren't what they appear to be? Those first 10 to 20 years are going to be really tough for them. Too many mistakes they can't cover up and they are toast. This means they may need to take over a third world country or someplace where the government has complete control over the media such as North Korea then they can handle the mistakes till they get their numbers up and figure out solutions.
46,980
If 1,000 Aliens **secretly** invaded earth would they take over the earth and start anew? These Aliens crash landed on our planet long ago, so their technology for the most part is destroyed. The only thing they manage to retained are advanced weapons that can destroy Nuclear Weapons without nuclear fallout occurring. These Aliens have the special and unique ability to change/manipulate their cellular structure. (They have complete control over their anatomies and bodies of themselves, including skin, nails, fat, muscles, blood, metabolism, nerves, etc., allowing them to freely alter and manipulate them. For example they can grow additional appendages and body-parts, remove them or otherwise manipulate them, in visible, chemical and cellular/sub-cellular levels.) Each one are in the main Countries there are 10 stationed per country these countries are: Russia, Italy, Brazil, India, France, United Kingdom, Germany, Japan, China, and The United States of America. The other 900 are located in other countries but are meant to stay incognito until they are given the signal. These Aliens goal are to start anew. To become the apex species of Earth and rule. Their government for now is kind of like a council. The ten in each country share a collective hive mind. **Only these certain ten in each country have the hive mind.** So the ten in France share a hive mind with each other, the ten in china share a hivemind with each other, etc etc. They can also reproduce with humans and other Aliens. They take on average 5 months before the child is born and they generally have more than one kid per pregnancy. They can become female or male depending on how they changed their bodies. Their shape-shifting abilities are detailed enough to bypass highly sensitive eye-scans and voice-scans. They are basically immortal as they can stay young forever. They can be killed only in a few ways, destroying their brain 100% completely, though few modify themselves to avoid suffering that fate. Completely destroying their bodies is another way. Though keeping them locked up is a option but it is not easy. How would they go about taking over? EDIT: While pregnant they can not use their shape changing abilties at all. They are basically human with a weak healing factor while pregnant
2016/07/12
[ "https://worldbuilding.stackexchange.com/questions/46980", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/22813/" ]
"the only technology they manage to retain are advanced weapons that can destroy nueclear weapons without fallout" Why is this the technology they choose to keep? If they have advanced weaponry stronger than humanity's strongest most terrible weapons, then they can wipe out entire cities with ease. They could invade secretly, but there's not much point when they can simply wipe out the current inhabitants and start a new purebred race of their own species. If your aliens truly want to hide, give them technology that can help them hide, or none at all, since they seem to be perfectly capable of hiding very well. Perhaps though, they may have a weakness that allows someone to see through their cover, for the sake of conflict. Currently these creatures are totally capable of taking over the earth unopposed, and, depending on whether their methods are peaceful, like in the answer above, or violent, they could overtake the human race very quickly.
Easily. So far this collection of aliens seem to be immortal. As @MolbOrg stated all they need to do is multiply. You say it takes 5 months to get 2 or more extra aliens. So, in five months you have a minimum of 3000 aliens. Still not very impressive except for the fact that they are IMMORTAL. Remember you said aliens survive if they retain party of their brain, go octopus . You can easily populate humans. This all seems kinda boring to me so here's the other option for a fast and easy destruction of most humans on earth. Nukes!. Shape shifting aliens are trying to destroy earth via our own nukes. They shape shift, I'm sure they can find our nukes. They then send nukes everywhere, MAD comes into effect, and the works ends as we know it. Immortal aliens stay in non nuked areas (the mountains). The only downside is that they have to deal with radiation for a long time.
46,980
If 1,000 Aliens **secretly** invaded earth would they take over the earth and start anew? These Aliens crash landed on our planet long ago, so their technology for the most part is destroyed. The only thing they manage to retained are advanced weapons that can destroy Nuclear Weapons without nuclear fallout occurring. These Aliens have the special and unique ability to change/manipulate their cellular structure. (They have complete control over their anatomies and bodies of themselves, including skin, nails, fat, muscles, blood, metabolism, nerves, etc., allowing them to freely alter and manipulate them. For example they can grow additional appendages and body-parts, remove them or otherwise manipulate them, in visible, chemical and cellular/sub-cellular levels.) Each one are in the main Countries there are 10 stationed per country these countries are: Russia, Italy, Brazil, India, France, United Kingdom, Germany, Japan, China, and The United States of America. The other 900 are located in other countries but are meant to stay incognito until they are given the signal. These Aliens goal are to start anew. To become the apex species of Earth and rule. Their government for now is kind of like a council. The ten in each country share a collective hive mind. **Only these certain ten in each country have the hive mind.** So the ten in France share a hive mind with each other, the ten in china share a hivemind with each other, etc etc. They can also reproduce with humans and other Aliens. They take on average 5 months before the child is born and they generally have more than one kid per pregnancy. They can become female or male depending on how they changed their bodies. Their shape-shifting abilities are detailed enough to bypass highly sensitive eye-scans and voice-scans. They are basically immortal as they can stay young forever. They can be killed only in a few ways, destroying their brain 100% completely, though few modify themselves to avoid suffering that fate. Completely destroying their bodies is another way. Though keeping them locked up is a option but it is not easy. How would they go about taking over? EDIT: While pregnant they can not use their shape changing abilties at all. They are basically human with a weak healing factor while pregnant
2016/07/12
[ "https://worldbuilding.stackexchange.com/questions/46980", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/22813/" ]
I just up-voted several of the previous things; the answer to your question is Yes, they would take over, so easily the plot is boring and nobody will care if they do. You have made your "hero" (the aliens) too powerful, this is like asking if my neighbor Joe will be able to eradicate the ants that have chosen to colonize his garden: Yes, yes he can, and he did it by heroically driving to the hardware store, heroically spending \$10 for some powder, and then heroically sprinkling it on the ant pile for about sixty seconds. An interesting story demands equalized heroes and villains; or underdog heroes against more powerful villains. A one-sided fight is predictable, so nobody is turning the page to see how this will turn out or the hero can possibly win. That is a boring story! As described, your aliens cannot possibly be in any serious danger. Pregnant women indistinguishable from humans are not going to be "detected". They move; how long they were pregnant can be covered by lies: My husband got a new job here and we had to move, so here we are, six months pregnant... (when it was really two). As mentioned, they can impersonate anybody, rob banks and blame the officers, steal from safes, kill and replace powerful politicians, etc. The hive mind makes them perfect collaborators: They can kill and replace top management of a major corporation, or the police force. You have to make them MUCH less powerful to have an interesting story.
This is your story and they will take over if you want them to take over. It feels like the most important variable is kind of random : do they get found out by the humans ? If not, they have no reason not to be able to take over, they are basically a better version of us. As MolbOrg said, just procreate and multiply. However, if they do get found out, things get interesting althought once again depends on your story. As Aify said, humans are pretty good at killing off other species, and we'd be very keen on killing them if they are trying to take over. On both sides, strategies can be thought up to beet the other species but considering we are over 7 billion with access to a huge amount of technology and thousands of years of experience killing each other, I'm guessing humans would win. The end result of a fight against humans and these aliens would obviously depend on how soon humans find out that a bunch of aliens are living among us and are trying to take over.
46,980
If 1,000 Aliens **secretly** invaded earth would they take over the earth and start anew? These Aliens crash landed on our planet long ago, so their technology for the most part is destroyed. The only thing they manage to retained are advanced weapons that can destroy Nuclear Weapons without nuclear fallout occurring. These Aliens have the special and unique ability to change/manipulate their cellular structure. (They have complete control over their anatomies and bodies of themselves, including skin, nails, fat, muscles, blood, metabolism, nerves, etc., allowing them to freely alter and manipulate them. For example they can grow additional appendages and body-parts, remove them or otherwise manipulate them, in visible, chemical and cellular/sub-cellular levels.) Each one are in the main Countries there are 10 stationed per country these countries are: Russia, Italy, Brazil, India, France, United Kingdom, Germany, Japan, China, and The United States of America. The other 900 are located in other countries but are meant to stay incognito until they are given the signal. These Aliens goal are to start anew. To become the apex species of Earth and rule. Their government for now is kind of like a council. The ten in each country share a collective hive mind. **Only these certain ten in each country have the hive mind.** So the ten in France share a hive mind with each other, the ten in china share a hivemind with each other, etc etc. They can also reproduce with humans and other Aliens. They take on average 5 months before the child is born and they generally have more than one kid per pregnancy. They can become female or male depending on how they changed their bodies. Their shape-shifting abilities are detailed enough to bypass highly sensitive eye-scans and voice-scans. They are basically immortal as they can stay young forever. They can be killed only in a few ways, destroying their brain 100% completely, though few modify themselves to avoid suffering that fate. Completely destroying their bodies is another way. Though keeping them locked up is a option but it is not easy. How would they go about taking over? EDIT: While pregnant they can not use their shape changing abilties at all. They are basically human with a weak healing factor while pregnant
2016/07/12
[ "https://worldbuilding.stackexchange.com/questions/46980", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/22813/" ]
Easily. So far this collection of aliens seem to be immortal. As @MolbOrg stated all they need to do is multiply. You say it takes 5 months to get 2 or more extra aliens. So, in five months you have a minimum of 3000 aliens. Still not very impressive except for the fact that they are IMMORTAL. Remember you said aliens survive if they retain party of their brain, go octopus . You can easily populate humans. This all seems kinda boring to me so here's the other option for a fast and easy destruction of most humans on earth. Nukes!. Shape shifting aliens are trying to destroy earth via our own nukes. They shape shift, I'm sure they can find our nukes. They then send nukes everywhere, MAD comes into effect, and the works ends as we know it. Immortal aliens stay in non nuked areas (the mountains). The only downside is that they have to deal with radiation for a long time.
So since nukes are in play, a critical componant of winning Globalthermal Nuclear Warfare is not to play... which is actually, why we had so many. It wasn't enough to be able to launch first, but launch second (second-strike capability). This relies on being able to see the inbound nukes with enough lead time to get all your nukes firing back. It was estimated in a first strike, 97% of your entire aresenal will be nutralized by the enemy. So aresanals were built with the understanding that 3% was enough harm the enemy enough on second strike to ensure a proper stand-off. It was MAD (in every sense of the reading of those letters). So here I am, an alien, watching these soon to be subject humans panic because on group put their primative nuclear missles too close to the other group and the other group is willing to start a war over this? If only they knew I could save them all. They'd practically do anything I said all because I have this one... small... gun... Back to nuclear warfare for a moment... the whole point here isn't to have a gun you want to fire, it's to have a gun that you just so happen to be cleaning when your daughter daughter brings her boyfriend home and you want to impress upon the lad how comitted you are to your daughter than to your own continued livelyhood as you know it. Of course, you'd never shoot the gun... you just need to that kid to think there is a situation where you would shoot that gun. Back to the alien's plan... so okay... we couldn't have known our meeting with the President during his trip to Dallas would have gone down the way it did... and okay, this cold war is cooling off... I wait twenty years to when Reagan comes back and rattles a few cages about the nuclear threat and then I go to him and say "Mr. President, I have this gun... it can stop your enemies nukes... but only I can use it... now, I'll keep you safe from your enemies... but I need some compensation from you, Mr. President... I'll let you know what I need when I need it... of course, if you don't want too... I have friends in Moscow... and Kennedy was on his way to give me his answer in Dallas and we all know how that turned out." That last one would be because as a Shape-Shifting alien, I like to keep the conspiracy theories going... and besides... I'm not lying... trip didn't turn out so well for both of us, Kennedy would have lept at the chance, what with his staunch anti-commie policies so he would be on his way to give me an answer, and I never said anything about me personally involved in that day. With that message delivered to Reagan, I head off to celebrate. After all, I'm pretty sure I made the most powerful man on the planet a deal he couldn't refuse and all I had to do was show him just one of our guns... now, I eliminated his greatest threat, am rewarded with just about anything on this planet I could want, and didn't lose a single of my very limited troops or my even more limited weapons. I think I'll go see that Taxi film my human friend Hinkly has been raving about. I don't see how any of this could go wrong.
46,980
If 1,000 Aliens **secretly** invaded earth would they take over the earth and start anew? These Aliens crash landed on our planet long ago, so their technology for the most part is destroyed. The only thing they manage to retained are advanced weapons that can destroy Nuclear Weapons without nuclear fallout occurring. These Aliens have the special and unique ability to change/manipulate their cellular structure. (They have complete control over their anatomies and bodies of themselves, including skin, nails, fat, muscles, blood, metabolism, nerves, etc., allowing them to freely alter and manipulate them. For example they can grow additional appendages and body-parts, remove them or otherwise manipulate them, in visible, chemical and cellular/sub-cellular levels.) Each one are in the main Countries there are 10 stationed per country these countries are: Russia, Italy, Brazil, India, France, United Kingdom, Germany, Japan, China, and The United States of America. The other 900 are located in other countries but are meant to stay incognito until they are given the signal. These Aliens goal are to start anew. To become the apex species of Earth and rule. Their government for now is kind of like a council. The ten in each country share a collective hive mind. **Only these certain ten in each country have the hive mind.** So the ten in France share a hive mind with each other, the ten in china share a hivemind with each other, etc etc. They can also reproduce with humans and other Aliens. They take on average 5 months before the child is born and they generally have more than one kid per pregnancy. They can become female or male depending on how they changed their bodies. Their shape-shifting abilities are detailed enough to bypass highly sensitive eye-scans and voice-scans. They are basically immortal as they can stay young forever. They can be killed only in a few ways, destroying their brain 100% completely, though few modify themselves to avoid suffering that fate. Completely destroying their bodies is another way. Though keeping them locked up is a option but it is not easy. How would they go about taking over? EDIT: While pregnant they can not use their shape changing abilties at all. They are basically human with a weak healing factor while pregnant
2016/07/12
[ "https://worldbuilding.stackexchange.com/questions/46980", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/22813/" ]
"the only technology they manage to retain are advanced weapons that can destroy nueclear weapons without fallout" Why is this the technology they choose to keep? If they have advanced weaponry stronger than humanity's strongest most terrible weapons, then they can wipe out entire cities with ease. They could invade secretly, but there's not much point when they can simply wipe out the current inhabitants and start a new purebred race of their own species. If your aliens truly want to hide, give them technology that can help them hide, or none at all, since they seem to be perfectly capable of hiding very well. Perhaps though, they may have a weakness that allows someone to see through their cover, for the sake of conflict. Currently these creatures are totally capable of taking over the earth unopposed, and, depending on whether their methods are peaceful, like in the answer above, or violent, they could overtake the human race very quickly.
So since nukes are in play, a critical componant of winning Globalthermal Nuclear Warfare is not to play... which is actually, why we had so many. It wasn't enough to be able to launch first, but launch second (second-strike capability). This relies on being able to see the inbound nukes with enough lead time to get all your nukes firing back. It was estimated in a first strike, 97% of your entire aresenal will be nutralized by the enemy. So aresanals were built with the understanding that 3% was enough harm the enemy enough on second strike to ensure a proper stand-off. It was MAD (in every sense of the reading of those letters). So here I am, an alien, watching these soon to be subject humans panic because on group put their primative nuclear missles too close to the other group and the other group is willing to start a war over this? If only they knew I could save them all. They'd practically do anything I said all because I have this one... small... gun... Back to nuclear warfare for a moment... the whole point here isn't to have a gun you want to fire, it's to have a gun that you just so happen to be cleaning when your daughter daughter brings her boyfriend home and you want to impress upon the lad how comitted you are to your daughter than to your own continued livelyhood as you know it. Of course, you'd never shoot the gun... you just need to that kid to think there is a situation where you would shoot that gun. Back to the alien's plan... so okay... we couldn't have known our meeting with the President during his trip to Dallas would have gone down the way it did... and okay, this cold war is cooling off... I wait twenty years to when Reagan comes back and rattles a few cages about the nuclear threat and then I go to him and say "Mr. President, I have this gun... it can stop your enemies nukes... but only I can use it... now, I'll keep you safe from your enemies... but I need some compensation from you, Mr. President... I'll let you know what I need when I need it... of course, if you don't want too... I have friends in Moscow... and Kennedy was on his way to give me his answer in Dallas and we all know how that turned out." That last one would be because as a Shape-Shifting alien, I like to keep the conspiracy theories going... and besides... I'm not lying... trip didn't turn out so well for both of us, Kennedy would have lept at the chance, what with his staunch anti-commie policies so he would be on his way to give me an answer, and I never said anything about me personally involved in that day. With that message delivered to Reagan, I head off to celebrate. After all, I'm pretty sure I made the most powerful man on the planet a deal he couldn't refuse and all I had to do was show him just one of our guns... now, I eliminated his greatest threat, am rewarded with just about anything on this planet I could want, and didn't lose a single of my very limited troops or my even more limited weapons. I think I'll go see that Taxi film my human friend Hinkly has been raving about. I don't see how any of this could go wrong.
46,980
If 1,000 Aliens **secretly** invaded earth would they take over the earth and start anew? These Aliens crash landed on our planet long ago, so their technology for the most part is destroyed. The only thing they manage to retained are advanced weapons that can destroy Nuclear Weapons without nuclear fallout occurring. These Aliens have the special and unique ability to change/manipulate their cellular structure. (They have complete control over their anatomies and bodies of themselves, including skin, nails, fat, muscles, blood, metabolism, nerves, etc., allowing them to freely alter and manipulate them. For example they can grow additional appendages and body-parts, remove them or otherwise manipulate them, in visible, chemical and cellular/sub-cellular levels.) Each one are in the main Countries there are 10 stationed per country these countries are: Russia, Italy, Brazil, India, France, United Kingdom, Germany, Japan, China, and The United States of America. The other 900 are located in other countries but are meant to stay incognito until they are given the signal. These Aliens goal are to start anew. To become the apex species of Earth and rule. Their government for now is kind of like a council. The ten in each country share a collective hive mind. **Only these certain ten in each country have the hive mind.** So the ten in France share a hive mind with each other, the ten in china share a hivemind with each other, etc etc. They can also reproduce with humans and other Aliens. They take on average 5 months before the child is born and they generally have more than one kid per pregnancy. They can become female or male depending on how they changed their bodies. Their shape-shifting abilities are detailed enough to bypass highly sensitive eye-scans and voice-scans. They are basically immortal as they can stay young forever. They can be killed only in a few ways, destroying their brain 100% completely, though few modify themselves to avoid suffering that fate. Completely destroying their bodies is another way. Though keeping them locked up is a option but it is not easy. How would they go about taking over? EDIT: While pregnant they can not use their shape changing abilties at all. They are basically human with a weak healing factor while pregnant
2016/07/12
[ "https://worldbuilding.stackexchange.com/questions/46980", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/22813/" ]
I just up-voted several of the previous things; the answer to your question is Yes, they would take over, so easily the plot is boring and nobody will care if they do. You have made your "hero" (the aliens) too powerful, this is like asking if my neighbor Joe will be able to eradicate the ants that have chosen to colonize his garden: Yes, yes he can, and he did it by heroically driving to the hardware store, heroically spending \$10 for some powder, and then heroically sprinkling it on the ant pile for about sixty seconds. An interesting story demands equalized heroes and villains; or underdog heroes against more powerful villains. A one-sided fight is predictable, so nobody is turning the page to see how this will turn out or the hero can possibly win. That is a boring story! As described, your aliens cannot possibly be in any serious danger. Pregnant women indistinguishable from humans are not going to be "detected". They move; how long they were pregnant can be covered by lies: My husband got a new job here and we had to move, so here we are, six months pregnant... (when it was really two). As mentioned, they can impersonate anybody, rob banks and blame the officers, steal from safes, kill and replace powerful politicians, etc. The hive mind makes them perfect collaborators: They can kill and replace top management of a major corporation, or the police force. You have to make them MUCH less powerful to have an interesting story.
Easily. So far this collection of aliens seem to be immortal. As @MolbOrg stated all they need to do is multiply. You say it takes 5 months to get 2 or more extra aliens. So, in five months you have a minimum of 3000 aliens. Still not very impressive except for the fact that they are IMMORTAL. Remember you said aliens survive if they retain party of their brain, go octopus . You can easily populate humans. This all seems kinda boring to me so here's the other option for a fast and easy destruction of most humans on earth. Nukes!. Shape shifting aliens are trying to destroy earth via our own nukes. They shape shift, I'm sure they can find our nukes. They then send nukes everywhere, MAD comes into effect, and the works ends as we know it. Immortal aliens stay in non nuked areas (the mountains). The only downside is that they have to deal with radiation for a long time.
46,980
If 1,000 Aliens **secretly** invaded earth would they take over the earth and start anew? These Aliens crash landed on our planet long ago, so their technology for the most part is destroyed. The only thing they manage to retained are advanced weapons that can destroy Nuclear Weapons without nuclear fallout occurring. These Aliens have the special and unique ability to change/manipulate their cellular structure. (They have complete control over their anatomies and bodies of themselves, including skin, nails, fat, muscles, blood, metabolism, nerves, etc., allowing them to freely alter and manipulate them. For example they can grow additional appendages and body-parts, remove them or otherwise manipulate them, in visible, chemical and cellular/sub-cellular levels.) Each one are in the main Countries there are 10 stationed per country these countries are: Russia, Italy, Brazil, India, France, United Kingdom, Germany, Japan, China, and The United States of America. The other 900 are located in other countries but are meant to stay incognito until they are given the signal. These Aliens goal are to start anew. To become the apex species of Earth and rule. Their government for now is kind of like a council. The ten in each country share a collective hive mind. **Only these certain ten in each country have the hive mind.** So the ten in France share a hive mind with each other, the ten in china share a hivemind with each other, etc etc. They can also reproduce with humans and other Aliens. They take on average 5 months before the child is born and they generally have more than one kid per pregnancy. They can become female or male depending on how they changed their bodies. Their shape-shifting abilities are detailed enough to bypass highly sensitive eye-scans and voice-scans. They are basically immortal as they can stay young forever. They can be killed only in a few ways, destroying their brain 100% completely, though few modify themselves to avoid suffering that fate. Completely destroying their bodies is another way. Though keeping them locked up is a option but it is not easy. How would they go about taking over? EDIT: While pregnant they can not use their shape changing abilties at all. They are basically human with a weak healing factor while pregnant
2016/07/12
[ "https://worldbuilding.stackexchange.com/questions/46980", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/22813/" ]
Based on the details of your *current* question (which sounds as though it has changed a lot from the original version), it seems to me that they **would likely succeed** in taking over. * They are effectively immortal, *and* can reproduce as well, which means that time is very much on their side. In addition to the sheer capacity for population growth, they can build power bases, accumulate wealth and knowledge and skill at unheard of levels. * Even with its range limits, the hive mind capabilities are a powerful advantage. Anything that anyone learns (in each country) is known to all of them. In a true hive mind that means not just information, but skills. How powerful the hive mind is depends on how quickly and fully the aliens can access it, and whether new descendants will be plugged into the country-hives. * They can blend in, and evade, better than anyone. Someone gets suspicious? Move and change your body to be a completely different person. * Speaking of which, it sounds like they could replace key people of power. Military commanders, businessmen, politicians, presidents. We know that they can physically take their exact form, perfectly, down to fingerprints and DNA. That means identical voice is possible as well. Manner of speech and psychological traits might be more difficult for them to reproduce. * They are motivated. Unless there is strife within their society, they are a fairly large group [even initially] which is unified towards a particular goal. A few comments on parts of your scenario that may complicate your storyline; * The anti-nuke tech seems pretty useless. Nukes are never a threat to them, since they're fully blended into human society. Perhaps they could use it at some point to cripple a country, by taking out all of its nuclear power plants. * The ability to reproduce with humans seems complicated. Would hybrid progeny still have the full set of capabilities of the alien race? If no, what's different? Certainly these hybrids would be conflicted individuals, who feel somewhere between super-human, and sub-alien. Likewise the 5 month gestation period would be highly suspicious to the human parent [if they're around], and any decent OBGYN. You could use some of that to add interest to your story. For example, the biggest threat to the alien race might just be their half-alien descendents.
**No, they would not take over. Once found, they would be destroyed very quickly.** How would they be found? Well, the moment they tried to take over they would have exposed themselves. "They can be killed only in a few ways, destroying their brain 100% completely, though few modify themselves to avoid suffering that fate. Completely destroying their bodies is another way." - **We don't need nukes to completely destroy a body (or a brain).** Grenades, and large missiles do a fantastic job of blowing bodies to bits.
46,980
If 1,000 Aliens **secretly** invaded earth would they take over the earth and start anew? These Aliens crash landed on our planet long ago, so their technology for the most part is destroyed. The only thing they manage to retained are advanced weapons that can destroy Nuclear Weapons without nuclear fallout occurring. These Aliens have the special and unique ability to change/manipulate their cellular structure. (They have complete control over their anatomies and bodies of themselves, including skin, nails, fat, muscles, blood, metabolism, nerves, etc., allowing them to freely alter and manipulate them. For example they can grow additional appendages and body-parts, remove them or otherwise manipulate them, in visible, chemical and cellular/sub-cellular levels.) Each one are in the main Countries there are 10 stationed per country these countries are: Russia, Italy, Brazil, India, France, United Kingdom, Germany, Japan, China, and The United States of America. The other 900 are located in other countries but are meant to stay incognito until they are given the signal. These Aliens goal are to start anew. To become the apex species of Earth and rule. Their government for now is kind of like a council. The ten in each country share a collective hive mind. **Only these certain ten in each country have the hive mind.** So the ten in France share a hive mind with each other, the ten in china share a hivemind with each other, etc etc. They can also reproduce with humans and other Aliens. They take on average 5 months before the child is born and they generally have more than one kid per pregnancy. They can become female or male depending on how they changed their bodies. Their shape-shifting abilities are detailed enough to bypass highly sensitive eye-scans and voice-scans. They are basically immortal as they can stay young forever. They can be killed only in a few ways, destroying their brain 100% completely, though few modify themselves to avoid suffering that fate. Completely destroying their bodies is another way. Though keeping them locked up is a option but it is not easy. How would they go about taking over? EDIT: While pregnant they can not use their shape changing abilties at all. They are basically human with a weak healing factor while pregnant
2016/07/12
[ "https://worldbuilding.stackexchange.com/questions/46980", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/22813/" ]
I just up-voted several of the previous things; the answer to your question is Yes, they would take over, so easily the plot is boring and nobody will care if they do. You have made your "hero" (the aliens) too powerful, this is like asking if my neighbor Joe will be able to eradicate the ants that have chosen to colonize his garden: Yes, yes he can, and he did it by heroically driving to the hardware store, heroically spending \$10 for some powder, and then heroically sprinkling it on the ant pile for about sixty seconds. An interesting story demands equalized heroes and villains; or underdog heroes against more powerful villains. A one-sided fight is predictable, so nobody is turning the page to see how this will turn out or the hero can possibly win. That is a boring story! As described, your aliens cannot possibly be in any serious danger. Pregnant women indistinguishable from humans are not going to be "detected". They move; how long they were pregnant can be covered by lies: My husband got a new job here and we had to move, so here we are, six months pregnant... (when it was really two). As mentioned, they can impersonate anybody, rob banks and blame the officers, steal from safes, kill and replace powerful politicians, etc. The hive mind makes them perfect collaborators: They can kill and replace top management of a major corporation, or the police force. You have to make them MUCH less powerful to have an interesting story.
Yes. The shape changing ability alone is enough to allow them to live along side humans without discovery. Having children with humans may not help them since they are the ones carrying the child. If a human female can carry the alien baby then they think the baby is premature at 5 months. (you may have to expand on that part since the baby probably doesn't have a clue how to control its form and would be born looking like the original alien until it did.) Another thing you have to tell us is at what age do they become sexually mature. If they are going for maximum growth rate then they would all be female in form so they can get pregnant. If they get pregnant twice a year they will hit 5000 new aliens in a year. I'm going to assume that they want to blend in so they can't just pop out 5000 every year without drawing attention so they stick to 5000 let them mature and then have them all become female and deal with breeding while the original 1000 worry about hiding and organization. If it takes 10 years to reach maturity and they wait the 10 years each time, just to keep the math simple, then the grown rate would be: 1000 year 1. 5000 year 2. 17,000 year 12. 81,000 year 22. 401,000 year 32. 2,001,000 year 42. 10,001,000 year 52... In 50 years they hit 10 million. And that number is assuming they wait 10 years before having a burst of children. It would most likely be much faster and the kids spread out a bit more than twice in a year but the effect would be the same. In 10 years they would have enough to really take control of an area so they could grow undisturbed. In 20 years they would have communities all over. Before all of that once the initial group was done with the first group of kids they would place themselves in charge of the nuclear powers of the world and not even need their anti nuke weapon. Others have brought up what if they are found out and I think it is quite possible for them to be found out during child birth if the baby doesn't come out human. Also what happens when they die? Some are going to get into car accidents and have autopsies performed on them. Do they turn back? Are the organs obviously not human? Assuming they do look human are they human at a cellular level? Will a blood test show they aren't what they appear to be? Those first 10 to 20 years are going to be really tough for them. Too many mistakes they can't cover up and they are toast. This means they may need to take over a third world country or someplace where the government has complete control over the media such as North Korea then they can handle the mistakes till they get their numbers up and figure out solutions.
46,980
If 1,000 Aliens **secretly** invaded earth would they take over the earth and start anew? These Aliens crash landed on our planet long ago, so their technology for the most part is destroyed. The only thing they manage to retained are advanced weapons that can destroy Nuclear Weapons without nuclear fallout occurring. These Aliens have the special and unique ability to change/manipulate their cellular structure. (They have complete control over their anatomies and bodies of themselves, including skin, nails, fat, muscles, blood, metabolism, nerves, etc., allowing them to freely alter and manipulate them. For example they can grow additional appendages and body-parts, remove them or otherwise manipulate them, in visible, chemical and cellular/sub-cellular levels.) Each one are in the main Countries there are 10 stationed per country these countries are: Russia, Italy, Brazil, India, France, United Kingdom, Germany, Japan, China, and The United States of America. The other 900 are located in other countries but are meant to stay incognito until they are given the signal. These Aliens goal are to start anew. To become the apex species of Earth and rule. Their government for now is kind of like a council. The ten in each country share a collective hive mind. **Only these certain ten in each country have the hive mind.** So the ten in France share a hive mind with each other, the ten in china share a hivemind with each other, etc etc. They can also reproduce with humans and other Aliens. They take on average 5 months before the child is born and they generally have more than one kid per pregnancy. They can become female or male depending on how they changed their bodies. Their shape-shifting abilities are detailed enough to bypass highly sensitive eye-scans and voice-scans. They are basically immortal as they can stay young forever. They can be killed only in a few ways, destroying their brain 100% completely, though few modify themselves to avoid suffering that fate. Completely destroying their bodies is another way. Though keeping them locked up is a option but it is not easy. How would they go about taking over? EDIT: While pregnant they can not use their shape changing abilties at all. They are basically human with a weak healing factor while pregnant
2016/07/12
[ "https://worldbuilding.stackexchange.com/questions/46980", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/22813/" ]
Easily. So far this collection of aliens seem to be immortal. As @MolbOrg stated all they need to do is multiply. You say it takes 5 months to get 2 or more extra aliens. So, in five months you have a minimum of 3000 aliens. Still not very impressive except for the fact that they are IMMORTAL. Remember you said aliens survive if they retain party of their brain, go octopus . You can easily populate humans. This all seems kinda boring to me so here's the other option for a fast and easy destruction of most humans on earth. Nukes!. Shape shifting aliens are trying to destroy earth via our own nukes. They shape shift, I'm sure they can find our nukes. They then send nukes everywhere, MAD comes into effect, and the works ends as we know it. Immortal aliens stay in non nuked areas (the mountains). The only downside is that they have to deal with radiation for a long time.
This is your story and they will take over if you want them to take over. It feels like the most important variable is kind of random : do they get found out by the humans ? If not, they have no reason not to be able to take over, they are basically a better version of us. As MolbOrg said, just procreate and multiply. However, if they do get found out, things get interesting althought once again depends on your story. As Aify said, humans are pretty good at killing off other species, and we'd be very keen on killing them if they are trying to take over. On both sides, strategies can be thought up to beet the other species but considering we are over 7 billion with access to a huge amount of technology and thousands of years of experience killing each other, I'm guessing humans would win. The end result of a fight against humans and these aliens would obviously depend on how soon humans find out that a bunch of aliens are living among us and are trying to take over.
72,099,233
I have a durable function that calls a method that simply adds a row to an efcore object. It doesn't call db save. When I step through the code, and get to the for loop, it will immediately jump to the line after the for loop. If I step into the call to add the efcore object, and back to the for loop, it continues and loops to the next item. If I press F5 to let it go without debugging, it immediately "breaks" the for loop. It jumps out of the for loop where i wrote `//HERE!!!!!!` I'm pulling my hair out on this one. obligatory code: ```cs //foreach (stagingFileMap stagingFileMap in fileMaps) foreach (stagingFileMap stagingFileMap in fileMaps) { if (ActivitySyncHelper.IsSyncCancelled(aso, _configuration)) { break; } if (!string.IsNullOrEmpty(stagingFileMap.URL)) { // Ensure the url is valid try { string x = await GetTotalBytes(stagingFileMap.URL); double.TryParse(x, out double fileByteCount); if (fileByteCount > 0) { // Create or update the video in vimeo if (string.IsNullOrEmpty(stagingFileMap.VimeoId)) { // Azure won't be ready with its backups, so use confex host for video 'get' string title = stagingFileMap.FileName; if (stagingFileMap.FileName.Length > 127) { title = stagingFileMap.FileName.Substring(0, 127); } Video video = vimeoClient.UploadPullLinkAsync(stagingFileMap.URL, title, stagingFileMap.id, meetingIdFolder.Uri).Result; stagingFileMap.VimeoId = video.Id.ToString(); stagingFileMap.VimeoId = video.Id.ToString(); //HERE!!!!!! await syncLog.WriteInfoMsg($"Vimeo create {stagingFileMap.FileName}"); //HERE!!!!!! } else { // Attempt to pull the existing video and update it if (long.TryParse(stagingFileMap.VimeoId, out long videoId)) { Video video = vimeoClient.GetVideoAsync(videoId).Result; if (video.Id.HasValue) { Video res = await vimeoClient.UploadPullReplaceAsync(stagingFileMap.URL, video.Id.Value, fileByteCount); await syncLog.WriteInfoMsg($"Vimeo replace {stagingFileMap.FileName} id {res.Id}"); } } } break; } } catch (Exception ex) { // IDK what to do besides skip it and continue // log something once logging works await syncLog.WriteErrorMsg(aso, ex.Message); await syncLog.Save(); continue; } // We need to save here requently because if there is big error, all the work syncing to vimeo will be desync with the DB dbContext.Update(stagingFileMap); await dbContext.SaveChangesAsync(); await syncLog.Save(); } } await dbContext.DisposeAsync(); ``` ```cs public async Task WriteInfoMsg( string msg) { SyncAttemptDetail sad = new() { SyncAttemptId = _id, Message = msg, MsgLevel = SyncAttemptMessageLevel.Info, AddDate = DateTime.UtcNow, AddUser = "SYSTEM" }; await _dbContext.SyncAttemptDetail.AddAsync(sad); } ```
2022/05/03
[ "https://Stackoverflow.com/questions/72099233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1649043/" ]
You can use [clip-path](https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path) to clip elements (section) in some shape. I created a **rough example** just to show how it could work: ```css section { position: relative; } section > div { min-height: 600px; } section:not(:last-of-type) > div { clip-path: ellipse(125% 70% at 20% 0%); } section + section { margin-top: -50%; } .red { background-color: red; } .blue { background-color: blue; } section:not(:last-of-type):before { content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' version='1.2' viewBox='0 0 393 86'%3E%3Cpath fill='red' d='M-12 63s61-18.9 85-12c24 6.9 110 18.1 143 8C249 48.9 408-5 408-5v29S240.3 79.7 213 82C84 93-6 72.9-6 72.9z'/%3E%3C/svg%3E"); position: absolute; top: 50%; left: 0; right: 0; z-index: 500; } ``` ```html <section style="z-index: 3"> <div style="background: black;"> Content goes here... </div> </section> <section style="z-index: 2"> <div style="background: gray;"> Content goes here... </div> </section> <section style="z-index: 1"> <div style="background: lightgray;"> Content goes here... </div> </section> ``` You can use online clip-path generators like [Clippy](https://bennettfeely.com/clippy/) to create custom shape.
``` <section id="section_2" class="bg-2"> <div class="section-2-bg"> <!-- <h2>Section 2</h2> --> <div class="section-2-outer"> <div id="section_2_inner" class="section-2-inner"> <style media="screen"> #section_2_inner { position: relative; background-image: url(pattern_2.jpg); padding: 300px 0px 120px; width: 100%; min-height: 600px; } </style> <script type="text/javascript"> var height = document.getElementById('section_2_inner').offsetHeight; let radius7 = 40; if (height <= 650) { radius7 = 32 - (height - 400)/20; }else if (height <= 700) { radius7 = 45 - (height - 400)/20; }else if (height <= 1200) { radius7 = 60 - (height - 400)/20; }else { radius7 = 32 - (height/100); } var radi_result = `#section_2_inner { border-radius: 0% 0% 45% 5% / 50% 50% `+ radius7 +`% 5%; }`; var style = document.createElement('style'); style.innerHTML = radi_result; document.head.appendChild(style); </script> <div class="section-2-inner-content"> <!-- section 2 content --> <div class="container"> <div class="row"> <div class="col-md-12"> <h2 class="title">Section 2</h2> </div> <div class="col-md-6"> <article class=""> <h2>Lorem ipsum dolor sit amet</h2> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </article> </div> <div class="col-md-6"> <article class=""> <h2>Lorem ipsum dolor sit amet</h2> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </article> </div> <div class="col-md-6"> <article class=""> <h2>Lorem ipsum dolor sit amet</h2> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </article> </div> <div class="col-md-6"> <article class=""> <h2>Lorem ipsum dolor sit amet</h2> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </article> </div> <div class="col-md-6"> <article class=""> <h2>Lorem ipsum dolor sit amet</h2> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </article> </div> </div> </div> <!-- content end --> </div> </div> <img id="arc-2" src="arc-2.png" alt="" width="100%" height="auto"> </div> </div> <img class="food" src="food-2.png" alt="" width="30%" height="auto"> </section> ```
72,099,233
I have a durable function that calls a method that simply adds a row to an efcore object. It doesn't call db save. When I step through the code, and get to the for loop, it will immediately jump to the line after the for loop. If I step into the call to add the efcore object, and back to the for loop, it continues and loops to the next item. If I press F5 to let it go without debugging, it immediately "breaks" the for loop. It jumps out of the for loop where i wrote `//HERE!!!!!!` I'm pulling my hair out on this one. obligatory code: ```cs //foreach (stagingFileMap stagingFileMap in fileMaps) foreach (stagingFileMap stagingFileMap in fileMaps) { if (ActivitySyncHelper.IsSyncCancelled(aso, _configuration)) { break; } if (!string.IsNullOrEmpty(stagingFileMap.URL)) { // Ensure the url is valid try { string x = await GetTotalBytes(stagingFileMap.URL); double.TryParse(x, out double fileByteCount); if (fileByteCount > 0) { // Create or update the video in vimeo if (string.IsNullOrEmpty(stagingFileMap.VimeoId)) { // Azure won't be ready with its backups, so use confex host for video 'get' string title = stagingFileMap.FileName; if (stagingFileMap.FileName.Length > 127) { title = stagingFileMap.FileName.Substring(0, 127); } Video video = vimeoClient.UploadPullLinkAsync(stagingFileMap.URL, title, stagingFileMap.id, meetingIdFolder.Uri).Result; stagingFileMap.VimeoId = video.Id.ToString(); stagingFileMap.VimeoId = video.Id.ToString(); //HERE!!!!!! await syncLog.WriteInfoMsg($"Vimeo create {stagingFileMap.FileName}"); //HERE!!!!!! } else { // Attempt to pull the existing video and update it if (long.TryParse(stagingFileMap.VimeoId, out long videoId)) { Video video = vimeoClient.GetVideoAsync(videoId).Result; if (video.Id.HasValue) { Video res = await vimeoClient.UploadPullReplaceAsync(stagingFileMap.URL, video.Id.Value, fileByteCount); await syncLog.WriteInfoMsg($"Vimeo replace {stagingFileMap.FileName} id {res.Id}"); } } } break; } } catch (Exception ex) { // IDK what to do besides skip it and continue // log something once logging works await syncLog.WriteErrorMsg(aso, ex.Message); await syncLog.Save(); continue; } // We need to save here requently because if there is big error, all the work syncing to vimeo will be desync with the DB dbContext.Update(stagingFileMap); await dbContext.SaveChangesAsync(); await syncLog.Save(); } } await dbContext.DisposeAsync(); ``` ```cs public async Task WriteInfoMsg( string msg) { SyncAttemptDetail sad = new() { SyncAttemptId = _id, Message = msg, MsgLevel = SyncAttemptMessageLevel.Info, AddDate = DateTime.UtcNow, AddUser = "SYSTEM" }; await _dbContext.SyncAttemptDetail.AddAsync(sad); } ```
2022/05/03
[ "https://Stackoverflow.com/questions/72099233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1649043/" ]
```css *{ font-family: 'Open Sans'; } body{ margin: 0px; } img{ width: 100%; } section{ position: relative; } section svg { position: absolute; left: 0; top: 0; } section .arc-overlay { position: absolute; width: 100%; left: 0; top: 0; } section .st0 { fill: transparent; } @media screen and (max-width: 768px) { .content > div{ display: block !important; } .content .cnt-1{ max-width: 100% !important; } } ``` ```html <!doctype html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400&display=swap" rel="stylesheet"> <script src="https://code.jquery.com/jquery.min.js"></script> <script src="https://demo.zhardsoft.com/arc-pattern/svg-inject.js"></script> <script type="text/javascript"> SVGInject.setOptions({ useCache: false, copyAttributes: false, makeIdsUnique: false, afterInject: function(img, svg) { var svgElm=$(svg); var svgHeight=svgElm.height(); svgElm.parents('section').css({'background-position-y':'-'+svgHeight+'px'}); svgElm.parents('section').find('.arc-overlay').css({'height':svgHeight+'px','top':'-'+(svgHeight-1)+'px'}); svgElm.parents('section').find('svg').css({'top':'-'+(svgHeight-1)+'px',}); }, }); $(window).on('resize',function(){ $('section svg').each(function(){ var svgElm=$(this); var svgHeight=svgElm.height(); svgElm.parents('section').css({'background-position-y':'-'+svgHeight+'px'}); svgElm.parents('section').find('.arc-overlay').css({'height':svgHeight+'px','top':'-'+(svgHeight-1)+'px'}); svgElm.parents('section').find('svg').css({'top':'-'+(svgHeight-1)+'px',}); }) }) </script> </head> <body> <section style="min-height: 500px;background-image: url(https://demo.zhardsoft.com/arc-pattern/wp2733014.jpg);background-size: 100% auto;"> <div class="content" style="padding: 40px;padding-bottom: 150px"> <div style="display: flex;display: -inline-flex;display: -webkit-flex;width: 100%"> <div style="padding: 20px"><img src="https://demo.zhardsoft.com/arc-pattern/img1.png" style="width: 250px"></div> <div class="cnt-1" style="color: #EBEBEB;max-width: 50%"> <h1>ECOLOGICAL PRODUCTION</h1> We recycle all organic waste we produce, also, we obtain organic waste from other farms, restaurants, and food markets. The organic waste we collect allows a particular larva from the Hermetia illucens species, known commonly as black soldier fly larva (BSFL), to feeds on it and grow fatter. When the larva has developed to a pupa, it is cleaned, cooked and grided to a paste used as a high-quality protein and lipids perfectly suited as ecological animal feed, reducing the need for wild-sourced feed ingredients such as fishmeal which contributes to the global overfishing.</div> </div> </div> </section> <section style="min-height: 300px;background-image: url(https://demo.zhardsoft.com/arc-pattern/wp2732984.jpg);background-size: 100% auto;padding: 0 40px"> <div class="content" style="padding: 20px;padding-bottom: 40px"> <div style="display: flex;display: -inline-flex;display: -webkit-flex;width: 100%;justify-content: flex-end;"> <div class="cnt-1" style="color: #EBEBEB;max-width: 50%;text-align: right;flex-grow: 1"> <h1 style="color: #FDC403">LOCAL COMMUNITY<br>ENGAGEMENT.</h1> It is in our core believe that if you benefit the local community, the people there will add value to your business as well. For every site we establish a manufacturing facility, our project will add value to the community as whole. We will provide jobs for hundreds of local residents with positions available within our production, sales, administration, and management teams. We will also offer hundreds of local farmers opportunities to join our supply network, providing training, coaching, and financial support to help them adapt to a more intensive and efficient farming system. Through our research and development, anything learned or discovered will be shared with our farmers to produce more efficiently and a healthier product. One among many different local benefitting activities, is that we will arrange cleanup days where we offer students an extra income for their effort as well as courses in environment know-how and teach them the importance of keeping the environment healthy. </div> </div> <div class="arc-overlay" style="background-image: url(https://demo.zhardsoft.com/arc-pattern/wp2732984.jpg);background-size: 100% auto;-webkit-mask: url('https://demo.zhardsoft.com/arc-pattern/arc.svg') top/100% auto no-repeat"></div> <img src="https://demo.zhardsoft.com/arc-pattern/arc.svg" onload="SVGInject(this);"/> </section> </body> </html> ``` **For SVG** Add a path under the arc in your SVG, to cover the bottom of the pattern. This is used to manipulate the background to match the pattern below it. for the above pattern no additional path is needed <https://i.stack.imgur.com/qxsWV.png> the class name (path) in the SVG file must match the css style (.st0) you can change it with the class name you want. <https://i.stack.imgur.com/dhLa1.png>
[![enter image description here](https://i.stack.imgur.com/AH8gq.jpg)](https://i.stack.imgur.com/AH8gq.jpg) 1.make div for background as parent set pattern background 2. make div under set backgorund layer-1 3. adjust background using css
72,099,233
I have a durable function that calls a method that simply adds a row to an efcore object. It doesn't call db save. When I step through the code, and get to the for loop, it will immediately jump to the line after the for loop. If I step into the call to add the efcore object, and back to the for loop, it continues and loops to the next item. If I press F5 to let it go without debugging, it immediately "breaks" the for loop. It jumps out of the for loop where i wrote `//HERE!!!!!!` I'm pulling my hair out on this one. obligatory code: ```cs //foreach (stagingFileMap stagingFileMap in fileMaps) foreach (stagingFileMap stagingFileMap in fileMaps) { if (ActivitySyncHelper.IsSyncCancelled(aso, _configuration)) { break; } if (!string.IsNullOrEmpty(stagingFileMap.URL)) { // Ensure the url is valid try { string x = await GetTotalBytes(stagingFileMap.URL); double.TryParse(x, out double fileByteCount); if (fileByteCount > 0) { // Create or update the video in vimeo if (string.IsNullOrEmpty(stagingFileMap.VimeoId)) { // Azure won't be ready with its backups, so use confex host for video 'get' string title = stagingFileMap.FileName; if (stagingFileMap.FileName.Length > 127) { title = stagingFileMap.FileName.Substring(0, 127); } Video video = vimeoClient.UploadPullLinkAsync(stagingFileMap.URL, title, stagingFileMap.id, meetingIdFolder.Uri).Result; stagingFileMap.VimeoId = video.Id.ToString(); stagingFileMap.VimeoId = video.Id.ToString(); //HERE!!!!!! await syncLog.WriteInfoMsg($"Vimeo create {stagingFileMap.FileName}"); //HERE!!!!!! } else { // Attempt to pull the existing video and update it if (long.TryParse(stagingFileMap.VimeoId, out long videoId)) { Video video = vimeoClient.GetVideoAsync(videoId).Result; if (video.Id.HasValue) { Video res = await vimeoClient.UploadPullReplaceAsync(stagingFileMap.URL, video.Id.Value, fileByteCount); await syncLog.WriteInfoMsg($"Vimeo replace {stagingFileMap.FileName} id {res.Id}"); } } } break; } } catch (Exception ex) { // IDK what to do besides skip it and continue // log something once logging works await syncLog.WriteErrorMsg(aso, ex.Message); await syncLog.Save(); continue; } // We need to save here requently because if there is big error, all the work syncing to vimeo will be desync with the DB dbContext.Update(stagingFileMap); await dbContext.SaveChangesAsync(); await syncLog.Save(); } } await dbContext.DisposeAsync(); ``` ```cs public async Task WriteInfoMsg( string msg) { SyncAttemptDetail sad = new() { SyncAttemptId = _id, Message = msg, MsgLevel = SyncAttemptMessageLevel.Info, AddDate = DateTime.UtcNow, AddUser = "SYSTEM" }; await _dbContext.SyncAttemptDetail.AddAsync(sad); } ```
2022/05/03
[ "https://Stackoverflow.com/questions/72099233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1649043/" ]
```css *{ font-family: 'Open Sans'; } body{ margin: 0px; } img{ width: 100%; } section{ position: relative; } section svg { position: absolute; left: 0; top: 0; } section .arc-overlay { position: absolute; width: 100%; left: 0; top: 0; } section .st0 { fill: transparent; } @media screen and (max-width: 768px) { .content > div{ display: block !important; } .content .cnt-1{ max-width: 100% !important; } } ``` ```html <!doctype html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400&display=swap" rel="stylesheet"> <script src="https://code.jquery.com/jquery.min.js"></script> <script src="https://demo.zhardsoft.com/arc-pattern/svg-inject.js"></script> <script type="text/javascript"> SVGInject.setOptions({ useCache: false, copyAttributes: false, makeIdsUnique: false, afterInject: function(img, svg) { var svgElm=$(svg); var svgHeight=svgElm.height(); svgElm.parents('section').css({'background-position-y':'-'+svgHeight+'px'}); svgElm.parents('section').find('.arc-overlay').css({'height':svgHeight+'px','top':'-'+(svgHeight-1)+'px'}); svgElm.parents('section').find('svg').css({'top':'-'+(svgHeight-1)+'px',}); }, }); $(window).on('resize',function(){ $('section svg').each(function(){ var svgElm=$(this); var svgHeight=svgElm.height(); svgElm.parents('section').css({'background-position-y':'-'+svgHeight+'px'}); svgElm.parents('section').find('.arc-overlay').css({'height':svgHeight+'px','top':'-'+(svgHeight-1)+'px'}); svgElm.parents('section').find('svg').css({'top':'-'+(svgHeight-1)+'px',}); }) }) </script> </head> <body> <section style="min-height: 500px;background-image: url(https://demo.zhardsoft.com/arc-pattern/wp2733014.jpg);background-size: 100% auto;"> <div class="content" style="padding: 40px;padding-bottom: 150px"> <div style="display: flex;display: -inline-flex;display: -webkit-flex;width: 100%"> <div style="padding: 20px"><img src="https://demo.zhardsoft.com/arc-pattern/img1.png" style="width: 250px"></div> <div class="cnt-1" style="color: #EBEBEB;max-width: 50%"> <h1>ECOLOGICAL PRODUCTION</h1> We recycle all organic waste we produce, also, we obtain organic waste from other farms, restaurants, and food markets. The organic waste we collect allows a particular larva from the Hermetia illucens species, known commonly as black soldier fly larva (BSFL), to feeds on it and grow fatter. When the larva has developed to a pupa, it is cleaned, cooked and grided to a paste used as a high-quality protein and lipids perfectly suited as ecological animal feed, reducing the need for wild-sourced feed ingredients such as fishmeal which contributes to the global overfishing.</div> </div> </div> </section> <section style="min-height: 300px;background-image: url(https://demo.zhardsoft.com/arc-pattern/wp2732984.jpg);background-size: 100% auto;padding: 0 40px"> <div class="content" style="padding: 20px;padding-bottom: 40px"> <div style="display: flex;display: -inline-flex;display: -webkit-flex;width: 100%;justify-content: flex-end;"> <div class="cnt-1" style="color: #EBEBEB;max-width: 50%;text-align: right;flex-grow: 1"> <h1 style="color: #FDC403">LOCAL COMMUNITY<br>ENGAGEMENT.</h1> It is in our core believe that if you benefit the local community, the people there will add value to your business as well. For every site we establish a manufacturing facility, our project will add value to the community as whole. We will provide jobs for hundreds of local residents with positions available within our production, sales, administration, and management teams. We will also offer hundreds of local farmers opportunities to join our supply network, providing training, coaching, and financial support to help them adapt to a more intensive and efficient farming system. Through our research and development, anything learned or discovered will be shared with our farmers to produce more efficiently and a healthier product. One among many different local benefitting activities, is that we will arrange cleanup days where we offer students an extra income for their effort as well as courses in environment know-how and teach them the importance of keeping the environment healthy. </div> </div> <div class="arc-overlay" style="background-image: url(https://demo.zhardsoft.com/arc-pattern/wp2732984.jpg);background-size: 100% auto;-webkit-mask: url('https://demo.zhardsoft.com/arc-pattern/arc.svg') top/100% auto no-repeat"></div> <img src="https://demo.zhardsoft.com/arc-pattern/arc.svg" onload="SVGInject(this);"/> </section> </body> </html> ``` **For SVG** Add a path under the arc in your SVG, to cover the bottom of the pattern. This is used to manipulate the background to match the pattern below it. for the above pattern no additional path is needed <https://i.stack.imgur.com/qxsWV.png> the class name (path) in the SVG file must match the css style (.st0) you can change it with the class name you want. <https://i.stack.imgur.com/dhLa1.png>
> > > > --- > > > ```css body { color: #ffffff; font-family: Poppins, sans-serif; font-size: 16px; font-style: normal; font-weight: normal; letter-spacing: 0; text-decoration: none; } .global_container_ { float: none; height: auto; margin: 0 auto; position: relative; width: 1280px; background: #ffffff; } .rectangle-10-copy-holder { height: 3623px; position: relative; width: 1280px; background-image: url(brick2.jpg); } .col { min-height: 3095px; padding: 0 0 134px; position: relative; width: 1280px; background: url(images/layer_10.png) no-repeat; } .wrapper-3 { height: 2601px; position: relative; width: 1280px; background-image: url(brick.jpg); } .elements { margin-top: 10px; width: 100%; background-image: url("brick.jpg"); } .shape-7-copy-2 { left: 50%; position: absolute; top: 1100px; margin-left: -405px; } .shape-1 { left: 50%; position: absolute; top: 1026px; margin-left: -640px; } .about-us { left: 50%; position: absolute; top: 827px; width: 1070px; margin-left: -520px; } .ellipse-2-copy { float: left; height: 462px; margin: 18px 71px 0 0; width: 462px; border: 20px solid #e0330a; -webkit-border-radius: 50%; -moz-border-radius: 50%; border-radius: 50%; background: url(images/food.png) no-repeat; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; -webkit-box-shadow: -13.365098px -6.809857px 24px 0 rgba(0, 0, 0, 0.62); -moz-box-shadow: -13.365098px -6.809857px 24px 0 rgba(0, 0, 0, 0.62); box-shadow: -13.365098px -6.809857px 24px 0 rgba(0, 0, 0, 0.62); } .col-2 { float: right; position: relative; width: 400px; height: 600px; } .text { color: #ffc602; font-family: Barlow, sans-serif; font-size: 55px; font-weight: bold; text-align: left; margin-top: -20px; } .text-2 { font-size: 16px; color: #ffffff; font-family: Barlow, sans-serif; line-height: 1.6; float: right; margin-top: -20px; } .text-3 { left: 50%; position: absolute; top: 2470px; color: #ffc600; font-family: Barlow, sans-serif; font-size: 55px; font-weight: bold; line-height: 1.2; text-align: right; text-transform: uppercase; margin-left: 20px; } .ecological { height: 1385px; left: 50%; position: absolute; top: 1108px; width: 1280px; background: url(images/shape_5_copy_3.png) no-repeat 0 130px; margin-left: -640px; } .shape-5-copy-4-holder { left: 50%; padding: 4px 0 17px; position: absolute; top: 315px; width: 1280px; background: url(images/shape_5_copy_4.png) no-repeat; margin-left: -640px; } .shape-5-copy-5 { display: block; } .shape-5-copy { left: 50%; position: absolute; top: 230px; margin-left: -640px; } .shape-5-copy-2-holder { left: 50%; padding: 1px 0 14px; position: absolute; top: 0; width: 1280px; background: url(images/shape_5_copy_2.png) no-repeat; margin-left: -640px; } .shape-5-copy-7-holder { padding: 149px 0 17px; position: relative; width: 1280px; background: url(images/shape_5_copy_7.png) no-repeat; } .col-3 { min-height: 1166px; padding: 34px 0 33px; position: relative; width: 1280px; background: url(images/shape_5.png) no-repeat; } .wrapper-6 { height: 618px; left: 40.5px; margin: 0 auto; position: relative; width: 1199px; } .ellipse-7 { height: 500px; left: 50%; position: absolute; top: 0; width: 500px; border-top: 20px solid #e0330a; border-left: 20px solid #e0330a; border-bottom: 20px solid #e0330a; border-right: 20px solid #e0330a; -webkit-border-radius: 50%; -moz-border-radius: 50%; border-radius: 50%; background: url(images/food3.png) no-repeat -8px -5px; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; -webkit-box-shadow: -13.365098px -6.809857px 5px 0 rgba(155, 6, 6, 0.61); -moz-box-shadow: -13.365098px -6.809857px 5px 0 rgba(155, 6, 6, 0.61); box-shadow: -13.365098px -6.809857px 5px 0 rgba(155, 6, 6, 0.61); margin-left: 70.5px; } .text-4 { left: 50%; position: absolute; top: 420px; width: 730px; font-size: 20px; line-height: 32px; margin-left: -595.5px; } .text-5 { left: 50%; position: absolute; top: 346px; font-family: Barlow, sans-serif; font-size: 45px; font-weight: bold; text-align: center; text-transform: uppercase; margin-left: -570.5px; margin-top: 3px; } .text-6 { float: right; margin: 75px 0 0; width: 676px; font-size: 20px; line-height: 32px; } .ellipse-3-copy { float: left; height: 404px; margin: 18px 71px 0 0; width: 404px; border: 20px solid #e0330a; -webkit-border-radius: 50%; -moz-border-radius: 50%; border-radius: 50%; background: url(images/food2.png) no-repeat 1px 1px; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; -webkit-box-shadow: -13.365098px -6.809857px 24px 0 rgba(0, 0, 0, 0.62); -moz-box-shadow: -13.365098px -6.809857px 24px 0 rgba(0, 0, 0, 0.62); box-shadow: -13.365098px -6.809857px 24px 0 rgba(0, 0, 0, 0.62); } .ellipse-4-copy-2 { left: 50%; position: absolute; top: 0; margin-left: -345px; } .ellipse-4-copy-3 { left: 50%; position: absolute; top: 0; margin-left: -347px; } .ellipse-4-copy-holder { left: 50%; padding: 0 0 18px; position: absolute; top: 0; width: 1039px; background: url(images/ellipse_4_copy.png) no-repeat; margin-left: -399px; } .ellipse-4-copy-4-holder { left: 11.5px; margin: 0 auto; padding: 0 0 23px; position: relative; width: 1016px; background: url(images/ellipse_4_copy_4.png) no-repeat; } .ellipse-4-holder { left: 26.5px; margin: 0 auto; padding: 0 0 20px; position: relative; width: 963px; background: url(images/ellipse_4.png) no-repeat; } .ellipse-4 { display: block; left: 18px; margin: 0 auto; position: relative; } .ellipse-1-copy-3 { left: 50%; position: absolute; top: 0; margin-left: -640px; } .ellipse-1-copy-5 { left: 50%; position: absolute; top: 0; margin-left: -640px; } .ellipse-1 { left: 50%; position: absolute; top: 0; margin-left: -640px; } .ellipse-1-copy-2 { left: 50%; position: absolute; top: 0; margin-left: -640px; } .text-7 { left: 50%; position: absolute; top: 528px; color: #ffc602; font-size: 77.31771px; font-weight: bold; line-height: 82px; margin-left: -552px; } .text-8 { left: 50%; position: absolute; top: 627px; font-family: Barlow, sans-serif; font-size: 34px; font-weight: 500; margin-top: 80px; margin-left: -554px; } .layer-16 { left: 50%; position: absolute; top: 58px; margin-left: -516px; } .row-5 { left: 25.5px; margin: 37px auto 0; position: relative; width: 1229px; } .text-10 { left: 50%; position: absolute; top: 0; width: 620px; line-height: 24px; text-align: right; margin-left: -100px; } .wrapper-8 { float: left; margin: 13px 0 0; padding: 13px 0 0; position: relative; width: 130px; background: url(images/vector_smart_object_copy__12.jpg) no-repeat; } .new { height: 829px; left: 50%; position: absolute; top: 2794px; width: 1280px; background: url(images/vector_smart_object_5.png) no-repeat; margin-left: -640px; } .shape-9-holder { height: 715px; left: 50%; position: absolute; top: 114px; width: 1280px; background: url(images/shape_9.png) no-repeat; margin-left: -640px; } .vector-smart-object-5 { left: 50%; position: absolute; top: 247px; margin-left: -640px; } .vector-smart-object-copy-24-holder { left: 50%; padding: 105px 0 0; position: absolute; top: 210px; width: 1280px; background: url(images/vector_smart_object_copy__19.png) no-repeat; margin-left: -640px; } .vector-smart-object-holder { margin: 0 auto; padding: 70px 0 0; position: relative; right: 48px; width: 1184px; background: url(images/vector_smart_object_7.png) no-repeat; } .shape-8 { display: block; margin: 0 auto; position: relative; right: 171.5px; } .layer-17 { display: block; margin: 0 auto; position: relative; margin-left: 95px; margin-top: -170px; } .circle { height: 692px; left: 50%; position: absolute; top: 1px; width: 985px; margin-left: -574px; } .group-2 { height: 438px; left: 50%; position: absolute; top: 0; width: 438px; margin-left: -492.5px; } .ellipse-8-copy { height: 417px; left: 50%; position: absolute; top: 0; width: 417px; border: 20px solid #e0330a; -webkit-border-radius: 50%; -moz-border-radius: 50%; border-radius: 50%; background: url(images/food4.png) no-repeat -3px -3px; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; -webkit-box-shadow: -13.365098px -6.809857px 24px 0 rgba(0, 0, 0, 0.62); -moz-box-shadow: -13.365098px -6.809857px 24px 0 rgba(0, 0, 0, 0.62); box-shadow: -13.365098px -6.809857px 24px 0 rgba(0, 0, 0, 0.62); margin-left: -219px; } .group-2-copy { height: 330px; left: 50%; position: absolute; top: 182px; width: 330px; margin-left: 162.5px; } .ellipse-8-copy-2 { height: 320px; left: 50%; position: absolute; top: 0; width: 320px; border: 20px solid #ffc602; -webkit-border-radius: 50%; -moz-border-radius: 50%; border-radius: 50%; background: url(images/food5.png) no-repeat 2px 1px; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; margin-left: -165px; } .group-2-copy-2 { height: 430px; left: 50%; position: absolute; top: 262px; width: 430px; margin-left: -194.5px; } .ellipse-8-copy-3 { height: 415px; left: 50%; position: absolute; top: 0; width: 415px; border: 20px solid #ff4600; -webkit-border-radius: 50%; -moz-border-radius: 50%; border-radius: 50%; background: url(images/food6.png) no-repeat 2px 1px; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; margin-left: -215px; } .sile{ text-align: left; } #mySpan{ writing-mode: vertical-lr; transform: rotate(180deg); font-size: 16px; padding: 20px; } ``` ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <title>food</title> </head> <body> <!-- <div class="center"> <li>HOME</li> <li>PRODUCT</li> <li>PRICING</li> <li>CONTACT US</li> </div> --> <div class="global_container_"> <div class="bg-banner-about"> <div class="rectangle-10-copy-holder"> <div class="banner group"> <div class="col08"> <div class="wrapper-3"> <img class="shape-7-copy-2" src="images/shape_7_copy_2.png" alt="" width="1045" height="818"> <img class="shape-1" src="images/shape_1.png" alt="" width="755" height="503"> <div class="about-us group"> <div class="ellipse-2-copy"></div> <div class="col-2"> <h1 class="text">ABOUT US</h1> <h3 class="text-2"> Pete's Claws and Fins is a high-tech producer of ecological seafood. We use state-of-the-art, highly computerized equipment to monitor and manage our seafood to ensure it is of the highest possible quality. All equipment we use is developed by ourselves in-house. We are the only company operating such high-tech equipment. The company started its research and development 2016 by Peter Persson, a Swedish inventor who has designed and built automated and computer-controlled machines and robots for over 30 years. Peter has over the years developed an increasing personal interest for natural and unprocessed food, and though he could make difference with help of his high-tech knowhow. </h3> </div> </div> <p class="text-3">Local Community<br>Engagement.</p> <div class="ecological"> <div class="shape-5-copy-4-holder"> <img class="shape-5-copy-5" src="images/shape_5_copy_5.png" alt="" width="1280" height="1049"> </div> <img class="shape-5-copy" src="images/shape_5_copy.png" alt="" width="1280" height="1066"> <div class="shape-5-copy-2-holder"> <div class="shape-5-copy-7-holder"> <div class="col-3"> <div class="wrapper-6"> <div class="ellipse-7"></div> <p class="text-4">All our seafoods are ecologically produced. Our endeavor is not using resources from the wildlife. We are only using farm-raised animals for our production. Our production is free from using harmful chemicals that can contaminate the environment or the food products we produce. Instead, we use natural minerals and bacteria to break down our waste products into harmless, biodegradable compounds.</p> <p class="text-5">Ecological production</p> </div> <div class="row group"> <div class="ellipse-3-copy"></div> <p class="text-6">We recycle all organic waste we produce, also, we obtain organic waste from other farms, restaurants, and food markets. The organic waste we collect allows a particular larva from the <em class="text-style">Hermetia illucens</em> species, known commonly as black soldier fly larva (BSFL), to feeds on it and grow fatter. When the larva has developed to a pupa, it is cleaned, cooked and grided to a paste used as a high-quality protein and lipids perfectly suited as ecological animal feed, reducing the need for wild-sourced feed ingredients such as fishmeal which contributes to the global overfishing.</p> </div> </div> </div> </div> </div> <img class="ellipse-4-copy-2" src="images/ellipse_4_copy_2.png" alt="" width="985" height="686"> <img class="ellipse-4-copy-3" src="images/ellipse_4_copy_3.png" alt="" width="987" height="676"> <div class="ellipse-4-copy-holder"> <div class="ellipse-4-copy-4-holder"> <div class="ellipse-4-holder"> <img class="ellipse-4" src="images/food1.png" alt="" width="927" height="611"> </div> </div> </div> <img class="ellipse-1-copy-3" src="images/ellipse_1_copy_3.png" alt="" width="630" height="464"> <img class="ellipse-1-copy-5" src="images/ellipse_1_copy_5.png" alt="" width="601" height="430"> <img class="ellipse-1" src="images/ellipse_1.png" alt="" width="555" height="446"> <p class="text-7">We Are Using</p> <p class="text-8">tech and artificial intelligence (AI) To produce ecological food.</p> <img class="layer-16" src="images/logo2.png" alt="" width="222" height="207"> <div class="side"><span id="mySpan"> CONTACT&nbsp;US &nbsp; &nbsp; PRICING &nbsp; &nbsp; PRODUCT &nbsp; &nbsp; HOME&nbsp; &nbsp;</span> </div> </div> <div class="row-5 group"> <div class="wrapper-9"> <p class="text-10">It is in our core believe that if you benefit the local community, the people there will add value to your business as well. For every site we establish a manufacturing facility, our project will add value to the community as whole. We will provide jobs for hundreds of local residents with positions available within our production, sales, administration, and management teams. We will also offer hundreds of local farmers opportunities to join our supply network, providing training, coaching, and financial support to help them adapt to a more intensive and efficient farming system. Through our research and development, anything learned or discovered will be shared with our farmers to produce more efficiently and a healthier product. One among many different local benefitting activities, is that we will arrange cleanup days where we offer students an extra income for their effort as well as courses in environment know-how and teach them the importance of keeping the environment healthy.</p> </div> </div> </div> </div> <div class="new"> <div class="shape-9-holder"> <img class="vector-smart-object-5" src="images/vector_smart_object_6.png" alt="" width="1276" height="468"> <div class="vector-smart-object-copy-24-holder"> <div class="vector-smart-object-holder"> <img class="shape-8" src="images/shape_8.png" alt="" width="841" height="330"> <img class="layer-17" src="images/logo1.png" alt="" width="140" height="140"> </div> </div> </div> <div class="circle"> <div class="group-2"> <div class="ellipse-8-copy"></div> </div> <div class="group-2-copy"> <div class="ellipse-8-copy-2"></div> </div> <div class="group-2-copy-2"> <div class="ellipse-8-copy-3"></div> </div> </div> </div> </div> </div> </div> </div> </body> </h> ``` Heading
72,099,233
I have a durable function that calls a method that simply adds a row to an efcore object. It doesn't call db save. When I step through the code, and get to the for loop, it will immediately jump to the line after the for loop. If I step into the call to add the efcore object, and back to the for loop, it continues and loops to the next item. If I press F5 to let it go without debugging, it immediately "breaks" the for loop. It jumps out of the for loop where i wrote `//HERE!!!!!!` I'm pulling my hair out on this one. obligatory code: ```cs //foreach (stagingFileMap stagingFileMap in fileMaps) foreach (stagingFileMap stagingFileMap in fileMaps) { if (ActivitySyncHelper.IsSyncCancelled(aso, _configuration)) { break; } if (!string.IsNullOrEmpty(stagingFileMap.URL)) { // Ensure the url is valid try { string x = await GetTotalBytes(stagingFileMap.URL); double.TryParse(x, out double fileByteCount); if (fileByteCount > 0) { // Create or update the video in vimeo if (string.IsNullOrEmpty(stagingFileMap.VimeoId)) { // Azure won't be ready with its backups, so use confex host for video 'get' string title = stagingFileMap.FileName; if (stagingFileMap.FileName.Length > 127) { title = stagingFileMap.FileName.Substring(0, 127); } Video video = vimeoClient.UploadPullLinkAsync(stagingFileMap.URL, title, stagingFileMap.id, meetingIdFolder.Uri).Result; stagingFileMap.VimeoId = video.Id.ToString(); stagingFileMap.VimeoId = video.Id.ToString(); //HERE!!!!!! await syncLog.WriteInfoMsg($"Vimeo create {stagingFileMap.FileName}"); //HERE!!!!!! } else { // Attempt to pull the existing video and update it if (long.TryParse(stagingFileMap.VimeoId, out long videoId)) { Video video = vimeoClient.GetVideoAsync(videoId).Result; if (video.Id.HasValue) { Video res = await vimeoClient.UploadPullReplaceAsync(stagingFileMap.URL, video.Id.Value, fileByteCount); await syncLog.WriteInfoMsg($"Vimeo replace {stagingFileMap.FileName} id {res.Id}"); } } } break; } } catch (Exception ex) { // IDK what to do besides skip it and continue // log something once logging works await syncLog.WriteErrorMsg(aso, ex.Message); await syncLog.Save(); continue; } // We need to save here requently because if there is big error, all the work syncing to vimeo will be desync with the DB dbContext.Update(stagingFileMap); await dbContext.SaveChangesAsync(); await syncLog.Save(); } } await dbContext.DisposeAsync(); ``` ```cs public async Task WriteInfoMsg( string msg) { SyncAttemptDetail sad = new() { SyncAttemptId = _id, Message = msg, MsgLevel = SyncAttemptMessageLevel.Info, AddDate = DateTime.UtcNow, AddUser = "SYSTEM" }; await _dbContext.SyncAttemptDetail.AddAsync(sad); } ```
2022/05/03
[ "https://Stackoverflow.com/questions/72099233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1649043/" ]
```css *{ font-family: 'Open Sans'; } body{ margin: 0px; } img{ width: 100%; } section{ position: relative; } section svg { position: absolute; left: 0; top: 0; } section .arc-overlay { position: absolute; width: 100%; left: 0; top: 0; } section .st0 { fill: transparent; } @media screen and (max-width: 768px) { .content > div{ display: block !important; } .content .cnt-1{ max-width: 100% !important; } } ``` ```html <!doctype html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400&display=swap" rel="stylesheet"> <script src="https://code.jquery.com/jquery.min.js"></script> <script src="https://demo.zhardsoft.com/arc-pattern/svg-inject.js"></script> <script type="text/javascript"> SVGInject.setOptions({ useCache: false, copyAttributes: false, makeIdsUnique: false, afterInject: function(img, svg) { var svgElm=$(svg); var svgHeight=svgElm.height(); svgElm.parents('section').css({'background-position-y':'-'+svgHeight+'px'}); svgElm.parents('section').find('.arc-overlay').css({'height':svgHeight+'px','top':'-'+(svgHeight-1)+'px'}); svgElm.parents('section').find('svg').css({'top':'-'+(svgHeight-1)+'px',}); }, }); $(window).on('resize',function(){ $('section svg').each(function(){ var svgElm=$(this); var svgHeight=svgElm.height(); svgElm.parents('section').css({'background-position-y':'-'+svgHeight+'px'}); svgElm.parents('section').find('.arc-overlay').css({'height':svgHeight+'px','top':'-'+(svgHeight-1)+'px'}); svgElm.parents('section').find('svg').css({'top':'-'+(svgHeight-1)+'px',}); }) }) </script> </head> <body> <section style="min-height: 500px;background-image: url(https://demo.zhardsoft.com/arc-pattern/wp2733014.jpg);background-size: 100% auto;"> <div class="content" style="padding: 40px;padding-bottom: 150px"> <div style="display: flex;display: -inline-flex;display: -webkit-flex;width: 100%"> <div style="padding: 20px"><img src="https://demo.zhardsoft.com/arc-pattern/img1.png" style="width: 250px"></div> <div class="cnt-1" style="color: #EBEBEB;max-width: 50%"> <h1>ECOLOGICAL PRODUCTION</h1> We recycle all organic waste we produce, also, we obtain organic waste from other farms, restaurants, and food markets. The organic waste we collect allows a particular larva from the Hermetia illucens species, known commonly as black soldier fly larva (BSFL), to feeds on it and grow fatter. When the larva has developed to a pupa, it is cleaned, cooked and grided to a paste used as a high-quality protein and lipids perfectly suited as ecological animal feed, reducing the need for wild-sourced feed ingredients such as fishmeal which contributes to the global overfishing.</div> </div> </div> </section> <section style="min-height: 300px;background-image: url(https://demo.zhardsoft.com/arc-pattern/wp2732984.jpg);background-size: 100% auto;padding: 0 40px"> <div class="content" style="padding: 20px;padding-bottom: 40px"> <div style="display: flex;display: -inline-flex;display: -webkit-flex;width: 100%;justify-content: flex-end;"> <div class="cnt-1" style="color: #EBEBEB;max-width: 50%;text-align: right;flex-grow: 1"> <h1 style="color: #FDC403">LOCAL COMMUNITY<br>ENGAGEMENT.</h1> It is in our core believe that if you benefit the local community, the people there will add value to your business as well. For every site we establish a manufacturing facility, our project will add value to the community as whole. We will provide jobs for hundreds of local residents with positions available within our production, sales, administration, and management teams. We will also offer hundreds of local farmers opportunities to join our supply network, providing training, coaching, and financial support to help them adapt to a more intensive and efficient farming system. Through our research and development, anything learned or discovered will be shared with our farmers to produce more efficiently and a healthier product. One among many different local benefitting activities, is that we will arrange cleanup days where we offer students an extra income for their effort as well as courses in environment know-how and teach them the importance of keeping the environment healthy. </div> </div> <div class="arc-overlay" style="background-image: url(https://demo.zhardsoft.com/arc-pattern/wp2732984.jpg);background-size: 100% auto;-webkit-mask: url('https://demo.zhardsoft.com/arc-pattern/arc.svg') top/100% auto no-repeat"></div> <img src="https://demo.zhardsoft.com/arc-pattern/arc.svg" onload="SVGInject(this);"/> </section> </body> </html> ``` **For SVG** Add a path under the arc in your SVG, to cover the bottom of the pattern. This is used to manipulate the background to match the pattern below it. for the above pattern no additional path is needed <https://i.stack.imgur.com/qxsWV.png> the class name (path) in the SVG file must match the css style (.st0) you can change it with the class name you want. <https://i.stack.imgur.com/dhLa1.png>
``` <section id="section_2" class="bg-2"> <div class="section-2-bg"> <!-- <h2>Section 2</h2> --> <div class="section-2-outer"> <div id="section_2_inner" class="section-2-inner"> <style media="screen"> #section_2_inner { position: relative; background-image: url(pattern_2.jpg); padding: 300px 0px 120px; width: 100%; min-height: 600px; } </style> <script type="text/javascript"> var height = document.getElementById('section_2_inner').offsetHeight; let radius7 = 40; if (height <= 650) { radius7 = 32 - (height - 400)/20; }else if (height <= 700) { radius7 = 45 - (height - 400)/20; }else if (height <= 1200) { radius7 = 60 - (height - 400)/20; }else { radius7 = 32 - (height/100); } var radi_result = `#section_2_inner { border-radius: 0% 0% 45% 5% / 50% 50% `+ radius7 +`% 5%; }`; var style = document.createElement('style'); style.innerHTML = radi_result; document.head.appendChild(style); </script> <div class="section-2-inner-content"> <!-- section 2 content --> <div class="container"> <div class="row"> <div class="col-md-12"> <h2 class="title">Section 2</h2> </div> <div class="col-md-6"> <article class=""> <h2>Lorem ipsum dolor sit amet</h2> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </article> </div> <div class="col-md-6"> <article class=""> <h2>Lorem ipsum dolor sit amet</h2> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </article> </div> <div class="col-md-6"> <article class=""> <h2>Lorem ipsum dolor sit amet</h2> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </article> </div> <div class="col-md-6"> <article class=""> <h2>Lorem ipsum dolor sit amet</h2> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </article> </div> <div class="col-md-6"> <article class=""> <h2>Lorem ipsum dolor sit amet</h2> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </article> </div> </div> </div> <!-- content end --> </div> </div> <img id="arc-2" src="arc-2.png" alt="" width="100%" height="auto"> </div> </div> <img class="food" src="food-2.png" alt="" width="30%" height="auto"> </section> ```
72,099,233
I have a durable function that calls a method that simply adds a row to an efcore object. It doesn't call db save. When I step through the code, and get to the for loop, it will immediately jump to the line after the for loop. If I step into the call to add the efcore object, and back to the for loop, it continues and loops to the next item. If I press F5 to let it go without debugging, it immediately "breaks" the for loop. It jumps out of the for loop where i wrote `//HERE!!!!!!` I'm pulling my hair out on this one. obligatory code: ```cs //foreach (stagingFileMap stagingFileMap in fileMaps) foreach (stagingFileMap stagingFileMap in fileMaps) { if (ActivitySyncHelper.IsSyncCancelled(aso, _configuration)) { break; } if (!string.IsNullOrEmpty(stagingFileMap.URL)) { // Ensure the url is valid try { string x = await GetTotalBytes(stagingFileMap.URL); double.TryParse(x, out double fileByteCount); if (fileByteCount > 0) { // Create or update the video in vimeo if (string.IsNullOrEmpty(stagingFileMap.VimeoId)) { // Azure won't be ready with its backups, so use confex host for video 'get' string title = stagingFileMap.FileName; if (stagingFileMap.FileName.Length > 127) { title = stagingFileMap.FileName.Substring(0, 127); } Video video = vimeoClient.UploadPullLinkAsync(stagingFileMap.URL, title, stagingFileMap.id, meetingIdFolder.Uri).Result; stagingFileMap.VimeoId = video.Id.ToString(); stagingFileMap.VimeoId = video.Id.ToString(); //HERE!!!!!! await syncLog.WriteInfoMsg($"Vimeo create {stagingFileMap.FileName}"); //HERE!!!!!! } else { // Attempt to pull the existing video and update it if (long.TryParse(stagingFileMap.VimeoId, out long videoId)) { Video video = vimeoClient.GetVideoAsync(videoId).Result; if (video.Id.HasValue) { Video res = await vimeoClient.UploadPullReplaceAsync(stagingFileMap.URL, video.Id.Value, fileByteCount); await syncLog.WriteInfoMsg($"Vimeo replace {stagingFileMap.FileName} id {res.Id}"); } } } break; } } catch (Exception ex) { // IDK what to do besides skip it and continue // log something once logging works await syncLog.WriteErrorMsg(aso, ex.Message); await syncLog.Save(); continue; } // We need to save here requently because if there is big error, all the work syncing to vimeo will be desync with the DB dbContext.Update(stagingFileMap); await dbContext.SaveChangesAsync(); await syncLog.Save(); } } await dbContext.DisposeAsync(); ``` ```cs public async Task WriteInfoMsg( string msg) { SyncAttemptDetail sad = new() { SyncAttemptId = _id, Message = msg, MsgLevel = SyncAttemptMessageLevel.Info, AddDate = DateTime.UtcNow, AddUser = "SYSTEM" }; await _dbContext.SyncAttemptDetail.AddAsync(sad); } ```
2022/05/03
[ "https://Stackoverflow.com/questions/72099233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1649043/" ]
You can use [clip-path](https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path) to clip elements (section) in some shape. I created a **rough example** just to show how it could work: ```css section { position: relative; } section > div { min-height: 600px; } section:not(:last-of-type) > div { clip-path: ellipse(125% 70% at 20% 0%); } section + section { margin-top: -50%; } .red { background-color: red; } .blue { background-color: blue; } section:not(:last-of-type):before { content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' version='1.2' viewBox='0 0 393 86'%3E%3Cpath fill='red' d='M-12 63s61-18.9 85-12c24 6.9 110 18.1 143 8C249 48.9 408-5 408-5v29S240.3 79.7 213 82C84 93-6 72.9-6 72.9z'/%3E%3C/svg%3E"); position: absolute; top: 50%; left: 0; right: 0; z-index: 500; } ``` ```html <section style="z-index: 3"> <div style="background: black;"> Content goes here... </div> </section> <section style="z-index: 2"> <div style="background: gray;"> Content goes here... </div> </section> <section style="z-index: 1"> <div style="background: lightgray;"> Content goes here... </div> </section> ``` You can use online clip-path generators like [Clippy](https://bennettfeely.com/clippy/) to create custom shape.
``` body{ background-image: url(bg.png); background-size: contain; background-position: bottom; margin: 0; padding: 0; } .logo{ position: absolute; left: 100px; top: 100px; z-index: 999; } .bg-1, .bg-2, .bg-3{ padding: 100px 0; background-repeat: no-repeat; background-size: cover; background-position: bottom; width: 100%; height: auto; } .bg-1{ background-image: url(bg-111.png); padding-top: 0; z-index: 50; } .bg-1 .title{ color: #ffc602; font-size: 77px; margin-bottom: 50px: } .bg-1 .sub-title{ color: #fff; font-size: 34px; margin-bottom: 70px; } .bg-2 .food{ position: absolute; right: 0; bottom: 0px; z-index: 200; } .bg-3 .food{ position: absolute; left: 0; bottom: -25px; z-index: 200; } .about h2 { color: #ffc602; font-size: 55px; margin-bottom: 50px: } .about p { color: #fff; font-size: 15px; line-height: 1.8; margin-bottom: 50px: } #section_2 .title, #section_3 .title{ font-size: 55px; margin-bottom: 30px; } .article-1{ padding: 100px; z-index: 10; } section{ position: relative; } #section_2{ margin-top: -450px } #section_2 .section-2-outer{ position: relative; width: 100%; height: auto; } .section-2-inner-content{ margin-left: auto; margin-right: 2%; } #arc-2{ position: absolute; bottom: -120px; left: 0; z-index: 100; } #arc_3{ position: absolute; bottom: -110px; left: 0; z-index: 100; } ```
72,099,233
I have a durable function that calls a method that simply adds a row to an efcore object. It doesn't call db save. When I step through the code, and get to the for loop, it will immediately jump to the line after the for loop. If I step into the call to add the efcore object, and back to the for loop, it continues and loops to the next item. If I press F5 to let it go without debugging, it immediately "breaks" the for loop. It jumps out of the for loop where i wrote `//HERE!!!!!!` I'm pulling my hair out on this one. obligatory code: ```cs //foreach (stagingFileMap stagingFileMap in fileMaps) foreach (stagingFileMap stagingFileMap in fileMaps) { if (ActivitySyncHelper.IsSyncCancelled(aso, _configuration)) { break; } if (!string.IsNullOrEmpty(stagingFileMap.URL)) { // Ensure the url is valid try { string x = await GetTotalBytes(stagingFileMap.URL); double.TryParse(x, out double fileByteCount); if (fileByteCount > 0) { // Create or update the video in vimeo if (string.IsNullOrEmpty(stagingFileMap.VimeoId)) { // Azure won't be ready with its backups, so use confex host for video 'get' string title = stagingFileMap.FileName; if (stagingFileMap.FileName.Length > 127) { title = stagingFileMap.FileName.Substring(0, 127); } Video video = vimeoClient.UploadPullLinkAsync(stagingFileMap.URL, title, stagingFileMap.id, meetingIdFolder.Uri).Result; stagingFileMap.VimeoId = video.Id.ToString(); stagingFileMap.VimeoId = video.Id.ToString(); //HERE!!!!!! await syncLog.WriteInfoMsg($"Vimeo create {stagingFileMap.FileName}"); //HERE!!!!!! } else { // Attempt to pull the existing video and update it if (long.TryParse(stagingFileMap.VimeoId, out long videoId)) { Video video = vimeoClient.GetVideoAsync(videoId).Result; if (video.Id.HasValue) { Video res = await vimeoClient.UploadPullReplaceAsync(stagingFileMap.URL, video.Id.Value, fileByteCount); await syncLog.WriteInfoMsg($"Vimeo replace {stagingFileMap.FileName} id {res.Id}"); } } } break; } } catch (Exception ex) { // IDK what to do besides skip it and continue // log something once logging works await syncLog.WriteErrorMsg(aso, ex.Message); await syncLog.Save(); continue; } // We need to save here requently because if there is big error, all the work syncing to vimeo will be desync with the DB dbContext.Update(stagingFileMap); await dbContext.SaveChangesAsync(); await syncLog.Save(); } } await dbContext.DisposeAsync(); ``` ```cs public async Task WriteInfoMsg( string msg) { SyncAttemptDetail sad = new() { SyncAttemptId = _id, Message = msg, MsgLevel = SyncAttemptMessageLevel.Info, AddDate = DateTime.UtcNow, AddUser = "SYSTEM" }; await _dbContext.SyncAttemptDetail.AddAsync(sad); } ```
2022/05/03
[ "https://Stackoverflow.com/questions/72099233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1649043/" ]
```css *{ font-family: 'Open Sans'; } body{ margin: 0px; } img{ width: 100%; } section{ position: relative; } section svg { position: absolute; left: 0; top: 0; } section .arc-overlay { position: absolute; width: 100%; left: 0; top: 0; } section .st0 { fill: transparent; } @media screen and (max-width: 768px) { .content > div{ display: block !important; } .content .cnt-1{ max-width: 100% !important; } } ``` ```html <!doctype html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400&display=swap" rel="stylesheet"> <script src="https://code.jquery.com/jquery.min.js"></script> <script src="https://demo.zhardsoft.com/arc-pattern/svg-inject.js"></script> <script type="text/javascript"> SVGInject.setOptions({ useCache: false, copyAttributes: false, makeIdsUnique: false, afterInject: function(img, svg) { var svgElm=$(svg); var svgHeight=svgElm.height(); svgElm.parents('section').css({'background-position-y':'-'+svgHeight+'px'}); svgElm.parents('section').find('.arc-overlay').css({'height':svgHeight+'px','top':'-'+(svgHeight-1)+'px'}); svgElm.parents('section').find('svg').css({'top':'-'+(svgHeight-1)+'px',}); }, }); $(window).on('resize',function(){ $('section svg').each(function(){ var svgElm=$(this); var svgHeight=svgElm.height(); svgElm.parents('section').css({'background-position-y':'-'+svgHeight+'px'}); svgElm.parents('section').find('.arc-overlay').css({'height':svgHeight+'px','top':'-'+(svgHeight-1)+'px'}); svgElm.parents('section').find('svg').css({'top':'-'+(svgHeight-1)+'px',}); }) }) </script> </head> <body> <section style="min-height: 500px;background-image: url(https://demo.zhardsoft.com/arc-pattern/wp2733014.jpg);background-size: 100% auto;"> <div class="content" style="padding: 40px;padding-bottom: 150px"> <div style="display: flex;display: -inline-flex;display: -webkit-flex;width: 100%"> <div style="padding: 20px"><img src="https://demo.zhardsoft.com/arc-pattern/img1.png" style="width: 250px"></div> <div class="cnt-1" style="color: #EBEBEB;max-width: 50%"> <h1>ECOLOGICAL PRODUCTION</h1> We recycle all organic waste we produce, also, we obtain organic waste from other farms, restaurants, and food markets. The organic waste we collect allows a particular larva from the Hermetia illucens species, known commonly as black soldier fly larva (BSFL), to feeds on it and grow fatter. When the larva has developed to a pupa, it is cleaned, cooked and grided to a paste used as a high-quality protein and lipids perfectly suited as ecological animal feed, reducing the need for wild-sourced feed ingredients such as fishmeal which contributes to the global overfishing.</div> </div> </div> </section> <section style="min-height: 300px;background-image: url(https://demo.zhardsoft.com/arc-pattern/wp2732984.jpg);background-size: 100% auto;padding: 0 40px"> <div class="content" style="padding: 20px;padding-bottom: 40px"> <div style="display: flex;display: -inline-flex;display: -webkit-flex;width: 100%;justify-content: flex-end;"> <div class="cnt-1" style="color: #EBEBEB;max-width: 50%;text-align: right;flex-grow: 1"> <h1 style="color: #FDC403">LOCAL COMMUNITY<br>ENGAGEMENT.</h1> It is in our core believe that if you benefit the local community, the people there will add value to your business as well. For every site we establish a manufacturing facility, our project will add value to the community as whole. We will provide jobs for hundreds of local residents with positions available within our production, sales, administration, and management teams. We will also offer hundreds of local farmers opportunities to join our supply network, providing training, coaching, and financial support to help them adapt to a more intensive and efficient farming system. Through our research and development, anything learned or discovered will be shared with our farmers to produce more efficiently and a healthier product. One among many different local benefitting activities, is that we will arrange cleanup days where we offer students an extra income for their effort as well as courses in environment know-how and teach them the importance of keeping the environment healthy. </div> </div> <div class="arc-overlay" style="background-image: url(https://demo.zhardsoft.com/arc-pattern/wp2732984.jpg);background-size: 100% auto;-webkit-mask: url('https://demo.zhardsoft.com/arc-pattern/arc.svg') top/100% auto no-repeat"></div> <img src="https://demo.zhardsoft.com/arc-pattern/arc.svg" onload="SVGInject(this);"/> </section> </body> </html> ``` **For SVG** Add a path under the arc in your SVG, to cover the bottom of the pattern. This is used to manipulate the background to match the pattern below it. for the above pattern no additional path is needed <https://i.stack.imgur.com/qxsWV.png> the class name (path) in the SVG file must match the css style (.st0) you can change it with the class name you want. <https://i.stack.imgur.com/dhLa1.png>
``` <section class="bg-1"> <img class="hero" src="hero.png" alt="" width="100%" height="auto"> <img class="logo" src="logo.png" alt="" width="300px" height="auto"> <div class="container"> <div class="row"> <div class="col-md-12"> <h1 class="title">We Are Using </h1> <h3 class="sub-title">High-tech and artificial intelligence (AI) To produce ecological food.</h3> </div> <div class="col-md-6"> <img class="about-img" src="about.png" alt="Food" width="70%" height="auto"> </div> <div class="col-md-6"> <article class="about"> <h2>About Us</h2> <p> Pete’s Claws and Fins is a high-tech producer of ecological seafood. We use state-of-the-art, highly computerized equipment to monitor and manage our seafood to ensure it is of the highest possible quality. All equipment we use is developed by ourselves in-house. We are the only company operating such high-tech equipment. The company started its research and development 2016 by Peter Persson, a Swedish inventor who has designed and built automated and computer-controlled machines and robots for over 30 years. Peter has over the years developed an increasing personal interest for natural and unprocessed food, and though he could make difference with help of his high-tech knowhow. </p> </article> </div> </div> </div> </div> </section> <section class="bg-2"> <img class="food" src="food-2.png" alt="" width="20%" height="auto"> <div class="container"> <div class="row"> <div class="col-md-6"> <article class=""> <h2>Lorem ipsum dolor sit amet</h2> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </article> </div> <div class="col-md-6"> <article class=""> <h2>Lorem ipsum dolor sit amet</h2> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </article> </div> <div class="col-md-6"> <article class=""> <h2>Lorem ipsum dolor sit amet</h2> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </article> </div> <div class="col-md-6"> <article class=""> <h2>Lorem ipsum dolor sit amet</h2> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </article> </div> <div class="col-md-6"> <article class=""> <h2>Lorem ipsum dolor sit amet</h2> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </article> </div> </div> </div> </section> <section class="bg-3"> <div class="container"> <div class="row"> <div class="col-md-6"> <article id="article-1"> <h2>Lorem ipsum dolor sit amet</h2> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </article> </div> <div class="col-md-6"> <article id="article-2"> <h2>Lorem ipsum dolor sit amet</h2> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </article> </div> <div class="col-md-6"> <article id="article-3"> <h2>Lorem ipsum dolor sit amet</h2> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam </p> </article> </div> <div class="col-md-6"> <article id="article-4"> <h2>Lorem ipsum dolor sit amet</h2> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </article> </div> </div> </div> <img class="food" src="food-2.png" alt="" width="20%" height="auto"> </section> ```